Unexpected null reference exceptions when using NSubstitute


I recently got some unexpected null reference exceptions in a test I was writing using MSTest and NSubstitute; I was setting up my mock to return a new instance of an object with a bunch of parameters set- my code looked like this;

iv_client.GetValuation("G1|12345", 10000, 2008, "08").Returns(new WebServiceResponse()
{
    Result = false,
    ErrorEnum = IdResponseCode.NoDataFound
});

However when access the value of my GetValuation call in the code it was always null? The solution it seems is to define the result in it’s own variable and then return that, rather than define it inline- like so;

var valuation = new WebServiceResponse()
{
    Result = false,
    ErrorEnum = IdResponseCode.NoDataFound
};

iv_client.GetValuation("G1|12345", 10000, 2008, "08").Returns(valuation);

There’s probably a good reason for this… but I don’t know what it is! Anyone care to shed some light on this in the comments?

  1. #1 by David on October 20, 2012 - 00:39

    This test works for me:

    https://gist.github.com/3921307

    GetValuation(..) should only return null if it is called for different arguments; whether the Returns(..) is specified inline or via a variable shouldn’t matter. Can you email me a bit more of the code so I can take a look at it?

    Regards,
    David

(will not be published)