My unit test gives me
"Configured setups: x => x.GetCount(It.IsAny(), It.IsAny()) No invocations performed."
This is the method below:
private IService Client = null;
public void CountChecks()
{
Client = new ServiceClient();
var _amount = Client.GetCount(value01, value01);
}
This is my test class:
public class CountChecksClassTests
{
private Mock<IService > service { get; set; }
private CountChecksClass { get; set; }
[TestInitialize]
public void Setup()
{
service = new Mock<IService>();
service.Setup(x => x.GetCount(It.IsAny<DateTime>(), It.IsAny<DateTime>()));
checker = new CountChecksClass ();
}
[TestMethod()]
public void GetCountTest()
{
checker.CountChecks();
service.Verify(x => x.GetCount(It.IsAny<DateTime>(), It.IsAny<DateTime>()));
}
}
When I debug the test, the method gets called. So, why am I getting a No invocations performed error? The error occurs at service.Verify(x => x.GetCount(It.IsAny<DateTime>(), It.IsAny<DateTime>()));
Every time you call CountChecks method - you create a new instance of IService, namely ServiceClient and assign it to your type's Client property, this piece:
public void CountChecks()
{
Client = new ServiceClient();
...
Hence your test method never calls into a mocked instance of the IService, instead it calls the ServiceClient created internally.
In order to fix this you need to inject your mocked instance of IService inside your CountChecksClass instance, e.g.:
checker = new CountChecksClass(service.Object);
...
public CountChecksClass(IService service)
{
Client = service;
}
And don't forget to remove Client = new ServiceClient(); from CountChecks method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With