unit-testing Test Doubles Using a mocking framework as a stub


The terms Mock and Stub can often become confused. Part of the reason for this is that many mocking frameworks also provide support for creating Stubs without the verification step associated with Mocking.

Rather than writing a new class to implement a stub as in the "Using a stub to supply canned responses" example, mocking frameworks can be used instead.

Using Moq:

var stub = new Mock<IRecordProvider>();
stub.Setup(provider => provider.GetRecords()).Returns(new List<Record> {
    new Record { Id = 1, Flag=false, Value="First" },
    new Record { Id = 2, Flag=true, Value="Second" },
    new Record { Id = 3, Flag=false, Value="Third" }

This achieves the same behaviour as the hand coded stub, and can be supplied to the system under test in a similar way:

var processed = sut.ProcessRecord(stub.Object);