Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moq No invocations performed

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>()));

like image 970
spmoolman Avatar asked Oct 18 '22 01:10

spmoolman


1 Answers

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.

like image 194
Yurii Avatar answered Oct 21 '22 03:10

Yurii