Skip to content

Instantly share code, notes, and snippets.

@franreyes
Last active September 9, 2024 09:17
Show Gist options
  • Save franreyes/575c81082ede41208784950d1a445cac to your computer and use it in GitHub Desktop.
Save franreyes/575c81082ede41208784950d1a445cac to your computer and use it in GitHub Desktop.
Use of test doubles with NSubstitute

Tools

NSubstitute

Example of spy

public interface CourseChat
{
    void Send(string message);
}

public class Course
{
    private readonly CourseChat _courseChat;

    public Course(CourseChat courseChat)
    {
        _courseChat = courseChat;
    }

    public void Start()
    {
        _courseChat.Send("Welcome to this marvellous course!!");
    }
}

public class CourseTest
{
    [Test]
    public void Send_A_Welcome_Message_In_The_Chat()
    {
        var courseChat = Substitute.For<CourseChat>();
        var course = new Course(courseChat);

        course.Start();

        courseChat.Received().Send("Welcome to this marvellous course!!"); // <- spying
    }
}

Example of stub

public interface StudentsRepository
{
    IEnumerable<Student> GetAll();
}

public class CourseReport
{
    private readonly StudentsRepository _studentsRepository;

    public CourseReport(StudentsRepository studentsRepository)
    {
        _studentsRepository = studentsRepository;
    }

    public double CalculateAgeAverage()
    {
        var students = _studentsRepository.GetAll();
        return students.Average(x => x.Age);
    }
}

public class CourseReportTest
{
    [Test]
    public void Calculate_Age_Average()
    {
        var repository = Substitute.For<StudentsRepository>();
        repository.GetAll().Returns(new[]                       // <- stubbing
        {
            new Student(20),
            new Student(25),
            new Student(30)
        });  
        var report = new CourseReport(repository);

        var result = report.CalculateAgeAverage();

        Assert.That(result, Is.EqualTo(25));
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment