Initial Steps for Service Layer Testing in ASP.NET Core (NUnit + Moq)
We will set up unit testing for the Service Layer using:
- ✅ NUnit (for testing framework)
- ✅ Moq (for mocking dependencies)
- ✅ FluentAssertions (for better assertions)
🔹 Step 1: Install Dependencies
Open the Package Manager Console in Visual Studio and run:
Alternatively, add dependencies in .csproj
:
🔹 Step 2: Create a Test Project
1️⃣ Right-click the solution → Add
→ New Project
2️⃣ Select "xUnit Test Project" or "NUnit Test Project"
3️⃣ Name it: DemoJune2024EmsSystem.Tests
4️⃣ Add reference to the main project (DemoJune2024EmsSystem
):
Right-click Test Project → Add Reference → Select Main Project
🔹 Step 3: Create a Sample Service to Test
In the main project (DemoJune2024EmsSystem
), define:
📌 IEmployeeService.cs
📌 EmployeeService.cs
🔹 Step 4: Create the Unit Test Class
Inside DemoJune2024EmsSystem.Tests
project, create:
📌 EmployeeServiceTests.cs
🔹 Step 5: Run the Tests
1️⃣ Open Test Explorer in Visual Studio (Test
→ Test Explorer
)
2️⃣ Click Run All to execute the tests
3️⃣ The tests should pass ✅
🔹 Explanation of Test Cases
Test Case | Expected Behavior |
---|---|
GetAllEmployees_ShouldReturnListOfEmployees | Returns a list of employees from the repository |
GetEmployeeById_ShouldReturnEmployee_WhenIdIsValid | Fetches an employee correctly |
GetEmployeeById_ShouldThrowException_WhenIdIsInvalid | Throws an exception for invalid IDs |
AddEmployee_ShouldReturnTrue_WhenValidEmployeeIsProvided | Successfully adds an employee |
AddEmployee_ShouldReturnFalse_WhenEmployeeIsNull | Fails to add a null employee |
AddEmployee_ShouldReturnFalse_WhenNameIsEmpty | Fails when employee name is empty |
🔹 Summary
✔ Service Layer Testing is essential because it verifies business logic.
✔ Moq is used to mock the Repository Layer, so tests run independently.
✔ NUnit and FluentAssertions make tests cleaner and more readable.
✔ These tests are fast and do not require a database connection.
No comments:
Post a Comment