Alex Gordon
Alex Gordon

Reputation: 60831

setting up a moq to mock a complex type using It.IsAny

I've been going through the plural sight tutorials on Moq. Using the AAA principal of arrange, act, assert, I've successfully mocked a method called GetDeviceSettingsForSerialNumber

[Test]
public void Interactions_should_be_called()
{
    //arange
    var mockConstructors = new Mock<IDeviceInteractions>();
    mockConstructors.Setup(x => x.GetDeviceSettingsForSerialNumber(It.IsAny<string>()));
    //Act
    var sut = new Device("123",123);
    sut.InitializeDeviceStatus();
    sut.InitializeDeviceSettings();
    //Assert
    mockConstructors.Verify();
} 

However, mocking a slightly more complex type is too difficult for me at this point, and I am seeking your guidance,.

The code that I am testing looks like this:

enter image description here

I've started off attempting the following test without luck:

   [Test]
    public void serviceDisposable_use_should_be_called()
    {
                    //arange
        var mockConstructors = new Mock<IWcfServiceProxy<PhysicianServiceContract>>();
        mockConstructors.Setup(x =>
            x.Use(It.IsAny < IWcfServiceProxy<PhysicianServiceContract>
                .GetPatientDeviceStatus(It.IsAny<int>()) >));
        //Act
        var sut = new Device("123",123);
        sut.InitializeDeviceStatus();
        //Assert
        mockConstructors.Verify();
    }

The specific issue is how to mimic the behavior: serviceDisposable.Use(x => x.GetPatientDeviceStatus(PatientId));

How do I mock the method GetPatientDeviceStatus?

Upvotes: 1

Views: 1132

Answers (1)

gembird
gembird

Reputation: 14053

Have a look at the place where the new keyword is used in the method InitializeDeviceStatus. Here because new is used the mocking is not possible because the instance is created in place directly.

Instead try to change the implementation so the instance you need to mock can be injected from outside somehow. This is done e.g. via constructor injection or by property injection. Or the method could get the instance of the WcfServiceProxy as parameter:

public void InitializeDeviceStatus(IWcfServiceProxy serviceDisposable)
{
    try 
    {
        DeviceStatus = serviceDisposable.Use(...);
    }
}

Then in the Test just inject the mock into the tested method:

[Test]
public void serviceDisposable_use_should_be_called()
{
    //arange
    ...

    // Inject the mock here
    sut.InitializeDeviceStatus(mockConstructors.Object);

    //Assert
    ...
}

Upvotes: 1

Related Questions