unit-testing Test Doubles Using a stub to supply canned responses

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

A stub is a light weight test double that provides canned responses when methods are called. Where a class under test relies on an interface or base class an alternative 'stub' class can be implemented for testing which conforms to the interface.

So, assuming the following interface,

public interface IRecordProvider {
    IEnumerable<Record> GetRecords();
}

If the following method was to be tested

public bool ProcessRecord(IRecordProvider provider)

A stub class that implements the interface can be written to return known data to the method being tested.

public class RecordProviderStub : IRecordProvider
{
    public IEnumerable<Record> GetRecords()
    {
        return 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 stub implementation can then be provided to the system under test, to influence it's behaviour.

var stub = new RecordProviderStub();
var processed = sut.ProcessRecord(stub);


Got any unit-testing Question?