Sometimes you want to test a class without using its real dependencies. Thatβs where test doubles come in.
πͺ Types of Test Doubles
- Stub: Returns fixed data (no real logic)
- Fake: Simple working implementation (not production-ready)
- Mock: Checks if certain actions happened (like method calls)
π§ Mocking Libraries
- Moq is the most popular for .NET
1
2
var mockLogger = new Mock<ILogger>();
mockLogger.Setup(l => l.Log(It.IsAny<string>())).Verifiable();
π Why Mock?
- Test only your code, not outside systems (like databases or web APIs)
- Make tests run faster and more reliably
π‘ Try It!
Install Moq with:
1
dotnet add package Moq
And try mocking an interface in your tests.
Next: Test-driven development (TDD)!