Reputation: 1163
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?
Upvotes: 0
Views: 3184
Reputation: 449
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!
Upvotes: 1
Reputation: 387647
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.
Upvotes: 1
Reputation: 1488
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
Upvotes: 0