Home > OS >  How to test an interface method that calls this interface another method?
How to test an interface method that calls this interface another method?

Time:05-08

I have a scenario where there is an interface with two methods:

public interface IStudent
{
    public void MethodA();
    public void MethodB();
}

And the implementation of MethodA calls MethodB as well as other interfaces' methods.

public class Student: IStudent
{
    private readonly IBook _book;
    private readonly IClassRoom _classRoom;
    private readonly ITeacher _teacher;

    public Student(
        IClassRoom classRoom,
        IBook book,
        ITeacher teacher)
    {
        _book = book;
        _classRoom = classRoom;
        _teacher = teacher;
    }

    public void MethodA()
    {
        _book.Get();
        _classRoom.Get();
        this.MethodB();
        ///Other logic...
    }

    public void MethodB()
    {
        _teacher.Get();
    }
}

I try to use moq to mock IBook, ITeacher, IClassRoom, and test MethodA by construction injection

public void IStudentMethodATest()
{
    var bookMock = new Moq<IClassRoom>().Setup(book => book.Get());
    var classRoomMock = new Moq<IClassRoom>().Setup(classRoom => classRoom.Get());

    var student = new Student() { classRoomMock.object, bookMock.object, null };
    student.MethodA();

    bookMock.Verify(book => book.Get(), Times.Once);
    classRoomMock.Verify(classRoom => classRoom.Get(), Times.Once);
}

But I don't know how to deal with the part of invoking MethodB in the MethodA.

Any suggestions?

CodePudding user response:

I think we might need to mock ITeacher interface as well because MethodA will call MethodB which means MethodB is a part of MethodA.

so that we need to test for it.

var bookMock = new Moq<IClassRoom>().Setup(book => book.Get());
var classRoomMock = new Moq<IClassRoom>().Setup(classRoom => classRoom.Get());
var teacherMock = new Moq<ITeacher>().Setup(teaher => teaher.Get());

var student = new Student() { classRoomMock.object, bookMock.object, teacherMock.object };
student.MethodA();
bookMock.Verify(book => book.Get(), Times.Once);
classRoomMock.Verify(classRoom => classRoom.Get(), Times.Once);

CodePudding user response:

first there are no access modifiers in the interface

public interface IStudent
{
    void MethodA();
    void MethodB();
}

secondly, the unit test should test the real Student class with fake dependencies:

var bookMock = new Moq<IBook>();
//if the function returns object
bookMock.Setup(book => book.Get()).Returns(something);
var classRoomMock = new Moq<IClassRoom>();
classRoomMock.Setup(classRoom => classRoom.Get()).Returns(something);
var teacherMock = new Moq<ITeacher>().Setup(teaher => teaher.Get());

var student = new Student() { classRoomMock.object, bookMock.object, teacherMock.object };
student.MethodA();
bookMock.Verify(book => book.Get(), Times.Once);
classRoomMock.Verify(classRoom => classRoom.Get(), Times.Once);

  • Related