Mocking and Test Doubles

Testing in isolation with fakes, stubs, and mocks

Posted by Rodrigo Castro on January 8, 2025

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)!