Reputation: 4463
I have this method which verify if a method is called. I am using xUnit and MOQ in C#.
[Fact]
public void VerifyIfInitCalled()
{
// Arrange
var mock = new Mock<ICal>();
var cal = new Cal(mock.Object);
// Act
cal.Init();
// Assert
mock.Verify(x => x.Init(), Times.Exactly(1));
}
and for my Cal class
public class Cal : ICal
{
private ICal _cal;
public Cal(ICal cal)
{
_cal = cal;
}
public void Init()
{
Console.WriteLine("Init called"); ;
}
}
But, I run the unit test, it fails with error Moq.MockException :
Expected invocation on the mock exactly 1 times, but was 0 times: x => x.Init()
although I have called the Init()
method.
Upvotes: 0
Views: 722
Reputation: 139
Your need to modify your Init()
to get your assert right
public void Init()
{
_cal.Init();
Console.WriteLine("Init called"); ;
}
and your interface ICal
need to have an Init()
member.
But clearly you have a conception problem you are implementing ICal
and passing it into the class constructor !!.
UPDATE
A unit test is specific to an implementation so your test method need to test the Cal
class.
If your class call an other service and you need to mock and setup a method call to get specific result you will use moq
Upvotes: 1