Unit Testing
Overview
Unit testing verifies small, isolated pieces of logic, usually functions or classes, without external dependencies.
Characteristics
- Fast execution
- Deterministic results
- No network or database dependency
- Focused on one behavior per test
flowchart LR
A[Test Case] --> B[Unit Under Test]
C[Mocked Dependencies] --> B
B --> D[Assertion]
Practical Example
private static decimal CalculateTax(decimal amount, decimal rate)
{
return Math.Round(amount * rate, 2);
}
[Fact]
public void CalculateTax_ReturnsExpectedAmount()
{
Assert.Equal(20.00m, CalculateTax(100m, 0.20m));
}
Production Guidance
- Name tests by behavior, not method name only
- Use fixtures for reusable setup
- Mock boundaries, not core business rules
Common Pitfalls
- Testing implementation details instead of outcomes
- Overusing mocks and hiding integration issues
- Writing flaky tests with time-based assumptions
Key Takeaways
- Unit tests provide fastest feedback loops.
- Isolated tests improve confidence during refactoring.
- Behavioral assertions keep tests robust over time.