C# Interview Question #97

What is mocking in unit testing?

SOLID, DI, Testing & Practical C# Mid-Level Intermediate

Quick Interview Answer

Mocking replaces a dependency with a controllable test double so that the unit under test can be tested without calling the real external component.

Detailed Explanation

Mocking replaces a dependency with a controllable test double so that the unit under test can be tested without calling the real external component.

For example, a ProductService test can mock IProductRepository instead of connecting to a real database.

Mocks are useful for verifying interactions and controlling dependency responses, but excessive mocking can make tests tightly coupled to implementation details. Fakes or integration tests can sometimes provide better confidence.

Code Example

var repository = new Mock<IProductRepository>();

repository
    .Setup(r => r.GetByIdAsync(1))
    .ReturnsAsync(new Product { Id = 1, Name = "Laptop" });

var service = new ProductService(repository.Object);

var product = await service.GetByIdAsync(1);

Assert.Equal("Laptop", product?.Name);