【问题标题】:setting up a moq to mock a complex type using It.IsAny使用 It.IsAny 设置最小起订量来模拟复杂类型
【发布时间】:2016-01-11 01:33:08
【问题描述】:

我一直在阅读有关 Moq 的 plural sight 教程。使用 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 =&gt; x.GetPatientDeviceStatus(PatientId));

如何模拟 GetPatientDeviceStatus 方法?

【问题讨论】:

  • 为了能够回答您的问题,我需要知道GetPatientDeviceStatus 的签名。顺便说一句,您不能使用 moq 模拟 C'tor,您必须进行一些重构才能使用 moq 测试 InitializeDeviceStatus。请添加GetPatientDeviceStatus的签名,然后我将能够发布完整的详细答案。

标签: c# visual-studio mocking nunit moq


【解决方案1】:

看看new方法在InitializeDeviceStatus方法中使用关键字的地方。这里因为使用了new,所以无法模拟,因为实例是直接就地创建的。

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

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

然后在 Test 中将 mock 注入到被测试的方法中:

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

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

    //Assert
    ...
}

【讨论】:

    猜你喜欢
    • 2022-01-16
    • 2011-01-25
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    • 2010-10-13
    • 1970-01-01
    • 2011-11-17
    • 1970-01-01
    相关资源
    最近更新 更多