简体   繁体   中英

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:

在此处输入图片说明

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?

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 eg 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
    ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM