简体   繁体   中英

How to test Interface Method

interface ITest
{
    void Run();
}

class Test : ITest
{
    void ITest.Run() => Run();
    public int Run()
    {
        //...
    }
}

Hello, how to verify that ITest.Run() execute "Run" of Test?

You could test this using a mocking framework like Moq:

public interface ITest
{
    void Run();
}

public class Test : ITest
{
    void ITest.Run() => Run();

    public virtual int Run()
    {
        return 1; // doesn’t matter, will be replaced by our mock
    }
}

The test would then look like this:

// arrange
Mock<Test> mock = new Mock<Test>();
mock.CallBase = true;
mock.Setup(t => t.Run()).Returns(1);

// act
ITest test = mock.Object;
test.Run();

// assert
mock.Verify(t => t.Run(), Times.Once());

This correctly throws when ITest.Run does not call the Run of Test . However, as you can see, doing this requires the Run method to be virtual so that the mock can overwrite it with its own implementation. This might not be desireable.

And ultimately, that test doesn't does not make any sense. When you unit test something, you want to unit test the behavior , not the implementation. So it shouldn't matter to you whether the explicit implementation ITest.Run calls another method on the object or not. You should only care about that the behavior of calling that method is correct.

To test interface is the easiest task! You can simply do it with Typemock Isolator (no virtual methods needed), take a look:

 [TestMethod, Isolated]
 public void TestRun()
 {
    //Arrange
    var fake = Isolate.Fake.Instance<ITest>();
    Isolate.WhenCalled(() => fake.Run()).CallOriginal();

    //Act
    fake.Run();

    //Assert
    Isolate.Verify.WasCalledWithAnyArguments(() => fake.Run());
}

You are mocking the interface, then setting the behavior to Run() method (it's optional), and after all you can verify the call was made.

Hope it helps!

It does not make sense to verify that Run is called unless your interface is used in another class. (not the class implementing it). So if you have a second class USING your ITest-interface, then it makes sense to verify that Run is called as you have done

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM