繁体   English   中英

设置最小起订量以使用It.IsAny模拟复杂类型

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

我一直在浏览Moq的复数视觉教程。 使用安排,行动,断言的AAA原理,我成功地模拟了一个名为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();
} 

但是,在这一点上,模拟一个稍微复杂的类型对于我来说太困难了,我正在寻求您的指导。

我正在测试的代码如下所示:

在此处输入图片说明

我开始尝试以下运气不好的测试:

   [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();
    }

具体的问题是如何模仿行为: serviceDisposable.Use(x => x.GetPatientDeviceStatus(PatientId));

如何模拟方法GetPatientDeviceStatus?

看一下InitializeDeviceStatus方法中使用new关键字的位置。 在这里,由于使用new ,因此无法进行模拟,因为直接在原地创建了实例。

而是尝试更改实现,以便可以从外部以某种方式注入您需要模拟的实例。 例如,这可以通过构造函数注入或属性注入来完成。 或者该方法可以获取WcfServiceProxy的实例作为参数:

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

然后在“测试”中,将模拟注入到测试方法中:

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

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

    //Assert
    ...
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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