C# and .NET • Modern C# baseline
Unit Tests and Testable Code
Test behavior through public contracts and make external dependencies controllable.
Unit tests check focused behavior quickly. Integration tests check real boundaries such as databases or HTTP services. A design that hides time, file access, and network operations inside domain logic is difficult to test; inject those dependencies or separate the pure logic from I/O.
Key points
- Test normal, boundary, and failure cases.
- Tests should assert externally meaningful behavior rather than private implementation details.
Example
using Xunit;
public class PriceTests
{
[Theory]
[InlineData(0, 0)]
[InlineData(4, 8)]
public void Total_multiplies_quantity_by_unit_price(int quantity, decimal expected)
{
Assert.Equal(expected, Price.Total(quantity, 2m));
}
}
What to expect
The test cases verify zero quantity and an ordinary quantity. The example uses xUnit.
Practice exercise
Add a test for invalid negative quantity and specify whether the method throws or returns an error.
Key idea: Tests are executable examples of a contract and should include edge behavior.