Search code examples
c#.netunit-testingxunitnsubstitute

Method mocked with NSabstitute returns '0' instead of HttpStatusCode.OK


Why do I get int value '0' after mocking my service and specifying return value as HttpStatusCode.OK?

  1. First I mock my service :
  private readonly IService service= Substitute.For<IService>();
  1. Then in the test :

    var statusCode = service.DoSomethingAndReturnHttpStatusCode(xmlDocument).Returns(HttpStatusCode.OK);
    
  2. In the end return value is statusCode = 0

What I would expect is : OK


Solution

  • Right answer would be

    Returns() will only apply to given combination of arguments, so other calls to this method will return a default value instead.

    Given argument will be compared to configured one. In your case configured instance of xmlDocument is different than instance passed to the method in the class under the test.

    You have two options:
    Ignore given argument - but lose some test coverage

    var result = 
       service.DoSomething(null).ReturnForAnyArgs(HttpStatusCode.OK);
    

    Verify given argument before returning expected value

    var result = service
        .DoSomething(Arg.Is<XmlDocument>(doc => doc != null))
        .Returns(HttpStatusCode.OK)