0

I am getting a below error while unit testing the piece of code

NSubstitute.Exceptions.ReceivedCallsException: Expected to receive a call matching error while unit testing NSubstitute.Exceptions.ReceivedCallsException HResult=0x80131500 Message=Expected to receive a call matching: enrollWithHelper("", "") Actually received no matching calls.

Source=NSubstitute StackTrace: at NSubstitute.Core.ReceivedCallsExceptionThrower.Throw(ICallSpecification callSpecification, IEnumerable1 matchingCalls, IEnumerable1 nonMatchingCalls, Quantity requiredQuantity) at NSubstitute.Routing.Handlers.CheckReceivedCallsHandler.Handle(ICall call) at NSubstitute.Routing.Route.Handle(ICall call) at NSubstitute.Proxies.CastleDynamicProxy.CastleForwardingInterceptor.Intercept(IInvocation invocation) at Castle.DynamicProxy.AbstractInvocation.Proceed() at Castle.DynamicProxy.AbstractInvocation.Proceed() at Castle.Proxies.ObjectProxy_1.enrollWithHelper(String name, String type) at MyProject.MyTest.processing_test_pass() in C:\MyProject\MyTest.cs:line 75

Framework: .NET Core

Unit Testing: NSubstitute

Here is my class under test

 public class MyService: IMysService
 {
   private readonly IRepository _repository;
   Private readonly IIoTHelper _iotHelper;  
   Private readonly HttpClient _httpClient;
   private Configuration _configuration; 

   public MyService(IRepository repository, IIoTHelper iotHelper, HttpClient httpClient )
   {
        _repository = repository;
        _iotHelper =iotHelper;
        _httpClient = httpClient ;
   }

   public bool CallService(JObject reqObj, out Status status)
   {
        bool provisioningSuccess = false;
        return PreProcessing(reqObj,out Status status); //private method
   }
}

Here is my private method

    private PreProcessing(JObject JosnObj, out Status status)
    {
        if (_configuration== null)
        {
            _configuration= _repository.GetConfigurations()                 
        }

       using (var client = this._httpClient)
       {
            var request = new {_configuration.Number,_configuration.Type};
            var response = client.PostAsJsonAsync("api/preprocess", request).Result;

            if (response.IsSuccessStatusCode)
            {
                  _iotHelper.enrollWithHelper(_configuration.Number,_configuration.Type);
            }
       }
    }

Here is my Configuration class

   public class Configuration 
   {
     public Configuration (string number, string type)
     {
        Number= number;
        Type= type;
     }      
     public string Number { get;}

     public string Type { get; }

   }

Here is my unit test code, where I want to make sure it reaches the private method

    protected override void InitializeTest()
    {
        this._repository = Substitute.For<IRepository>();
        this._iotHelper = Substitute.For<IIotHelper>();
    }

    [TestMethod]
    public void processing_test_pass()
    {
          //Arrange
        var messageHandler = new MockHttpMessageHandler("TEST VALUE", HttpStatusCode.OK);
        var httpClient = new HttpClient(messageHandler);


          JObject reqobj= new JObject(
          new JProperty("user", "username"),
          new JProperty("pass", "password"));

        Status status = new Status();

        //act
        var t = new MyService(this._repository,this._iotHelper, httpClient );
        bool success = t.CallService(reqobj, out status);
        //assert
        this._iotHelper.Received().enrollWithHelper("","");

    }

How would I test enrollWithHelper is called?

Also I am stuck due to error!

kudlatiger
  • 3,028
  • 8
  • 48
  • 98
  • The subject under test is not using the http handler you manually created in the test. It is using the one created within the private member – Nkosi Jan 16 '20 at 16:14
  • Instead of tightly coupling to the client, consider abstracting that out into an injectable service. – Nkosi Jan 16 '20 at 16:15
  • I do inject httpClient to the class under test. I have now updated the code in question. – kudlatiger Jan 17 '20 at 02:03
  • 1
    @kudlatiger, in the unit test code you need to call the method with parameters before the assert something like `var result=t.CallService(reqObj, status);` – Ajeet Kumar Jan 17 '20 at 02:14
  • @AjeetKumar "Received()" will do it. – kudlatiger Jan 17 '20 at 03:36
  • 1
    @kudlatiger, as per my understanding, the method to be tested needs to be called explicitly as `act`. I can see `Arrange` and `assert` but no the `act`. Otherwise, the private method shall never be called and the assert shall always fail. Please double check [nsubstitute official link](https://nsubstitute.github.io/help/received-calls/) – Ajeet Kumar Jan 17 '20 at 03:51
  • @AjeetKumar enrollWithHelper is a method and it called explicitly. question is around _configuration. – kudlatiger Jan 17 '20 at 03:54
  • I have updated with full exception details, also added missed "act" which was already there in the code but missed while typing in SO – kudlatiger Jan 17 '20 at 04:07
  • 1
    @kudlatiger Maybe try `ReceivedWithAnyArgs()` instead of `Received` and see if that helps. Also you can use `_iotHelper.ReceivedCalls()` to get a list of calls and inspect if it is receiving any calls during your test. You can also try using debugger (or tracing) to see if the `if (response.IsSuccessStatusCode)` branch is true and executes. – David Tchepak Jan 19 '20 at 12:08
  • issue resolved. test was not reaching enrollWithHelper method with right argument. @DavidTchepak you are right – kudlatiger Jan 20 '20 at 04:20

0 Answers0