跳到主要内容

Unit Testing

What is Unit Testing? (One-liner)

Unit testing verifies a single unit (method/class) in isolation.

Why we do it:

  • Catch bugs early
  • Refactor safely
  • Improve design (loose coupling)
  • Living documentation

What Do We Unit Test in ASP.NET Core?

Services, not controllers.

Why?

  • Services = business logic
  • Controllers = thin (HTTP glue)
  • Services are easy to test in isolation

✅ Test:

  • Services
  • Domain logic
  • Validation logic

❌ Don't test:

  • Database
  • HTTP calls
  • File system
  • Framework code

Golden Rule: AAA Pattern ⭐

Every test follows AAA:

Arrange → Act → Assert
// Arrange
var service = new MyService();

// Act
var result = service.DoSomething();

// Assert
Assert.Equal(expected, result);

🎯 Interview sentence:

"AAA makes tests readable, consistent, and focused."


xUnit Basics (Must-Know)

Attributes

[Fact][Theory][InlineData(1, 2, 3)]; // Single test // Data-driven test

Assertions

Assert.Equal()
Assert.True()
Assert.False()
Assert.Null()
Assert.NotNull()
Assert.Throws<T>()

That's enough for interviews.


Example Test (Classic)

[Fact]
public void Add_ShouldReturnCorrectSum()
{
// Arrange
var calculator = new Calculator();

// Act
var result = calculator.Add(2, 3);

// Assert
Assert.Equal(5, result);
}

📌 Clear name = clear intent


CRUD + Unit Testing (VERY IMPORTANT)

What to test in CRUD services:

  • Add → returns created entity
  • Get → returns correct data
  • Update → updates correctly
  • Delete → removes entity

Example assertion pattern:

Assert.NotEqual(Guid.Empty, response.Id);
Assert.Contains(response, list);

You're testing behavior, not database mechanics.


Mocking (Isolation Principle)

Why mock?

To isolate the unit under test.

If a service depends on:

  • Database
  • API
  • Another service

Mock it

Popular frameworks:

  • Moq (most common)
  • NSubstitute

🎯 Interview sentence:

"Mocks allow us to test logic without external dependencies."


What NOT to Do ❌

❌ Test implementation details ❌ Test private methods ❌ Use real database in unit tests ❌ Write logic-heavy tests ❌ Make tests depend on each other ❌ Slow tests


9️⃣ Unit Tests vs Integration Tests

Unit TestIntegration Test
FastSlower
IsolatedReal dependencies
Mocks usedReal DB / APIs
Test logicTest wiring

📌 Interviewers love this comparison.


Test Naming Convention (Easy Win)

MethodName_Scenario_ExpectedResult

Example:

AddCountry_ValidRequest_ReturnsCountry

One-Paragraph Interview Answer

"Unit testing verifies individual units like service methods in isolation. In ASP.NET Core, we usually test services using xUnit and follow the Arrange-Act-Assert pattern. Dependencies such as databases or APIs are mocked to keep tests fast and reliable. Unit tests help catch bugs early, enable safe refactoring, and act as living documentation."


If You Remember ONLY 5 Things

  1. Test services, not controllers
  2. Follow AAA
  3. Use xUnit
  4. Mock dependencies
  5. Test behavior, not implementation