Search code examples
unit-testingmockingnsubstitutestubbing

NSubstitute: Trouble mocking a syntatic sugar getter method associated with a member variable with No corresponding setter


For my .NET C# application, I'm using a third-party e-faxing software named efaxdeveloper.com

I needed to mock efaxdeveloper.com's software OutboundResponse object.

Please keep in mind that since it's 3rd party, I obviously can Not modify the 3rd-party dlls.

In the eFaxDeveloper.dll, the following is the code for the OutboundResponse class:

using System.Runtime.InteropServices;

namespace J2.eFaxDeveloper.Outbound
{
    //
    // Summary:
    //     oubound response
    [ClassInterface(ClassInterfaceType.AutoDual)]
    [System.Runtime.Serialization.DataContractAttribute(Namespace = "")]
    public class OutboundResponse
    {
        public OutboundResponse();

        //
        // Summary:
        //     Unique client specified transmission identifier
        public string TransmissionID { get; }
        //
        // Summary:
        //     eFax Developer™ transmission identifier
        public string DOCID { get; }
        //
        // Summary:
        //     J2.eFaxDeveloper.Outbound.StatusCode
        public StatusCode StatusCode { get; }
        //
        // Summary:
        //     Status description
        public string StatusDescription { get; }
        //
        // Summary:
        //     J2.eFaxDeveloper.Outbound.ErrorLevel
        public ErrorLevel ErrorLevel { get; }
        //
        // Summary:
        //     Error message
        public string ErrorMessage { get; }
    }
}

Since it only has getters, I tried the following snippet of code:

    OutboundResponse outboundResponseInQuestion = Substitute.For<OutboundResponse>();

    outboundResponseInQuestion.TransmissionID.Returns("someTransmissionID");

Unfortunately, outboundResponseInQuestion.TransmissionID throws

'outboundResponseInQuestion.TransmissionID' threw an exception of type 'System.NullReferenceException'

I can Not create an Interface for the OutboundResponse class so could someone please tell me how I can mock said object using NSubstitute and make it return the proper values?


Solution

  • NSubstitute can not mock this type because it does not have virtual members. (We also can't manually create a sub-type of OutboundResponse that overrides the getters and exposes setters and use that for testing, for the same reason.)

    You may have an easier time by creating an interface that encapsulates the entirety of the required behaviour from the 3rd party library (facade pattern) and testing your code's interaction with that interface. You can then separately test your implementation of that interface produces correct results when calling the 3rd party library. These may be integration or manual tests.

    <shamelessplug>I have previously written a bit about the downsides of mocking types we don't own that you may find useful.</shamelessplug>