C# 设置moq以使用它模拟复杂类型。IsAny

C# 设置moq以使用它模拟复杂类型。IsAny,c#,visual-studio,mocking,nunit,moq,C#,Visual Studio,Mocking,Nunit,Moq,我一直在看有关Moq的教程。使用arrange、act、assert的AAA原则,我成功地模拟了一个名为GetDeviceSettingsForSerialNumber的方法 [Test] public void Interactions_should_be_called() { //arange var mockConstructors = new Mock<IDeviceInteractions>(); mockConstructors.Setup(x =

我一直在看有关Moq的教程。使用arrange、act、assert的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();
} 
[测试]
公共无效交互应被称为()
{
//阿兰奇
var mockConstructors=new Mock();
mockConstructors.Setup(x=>x.GetDeviceSettingsForSerialNumber(It.IsAny());
//表演
var sut=新装置(“123”,123);
sut.InitializeDeviceStatus();
sut.初始化设备设置();
//断言
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();
    }
[测试]
公共作废服务一次性使用应称为()
{
//阿兰奇
var mockConstructors=new Mock();
mockConstructors.Setup(x=>
x、 使用(It.IsAny);
//表演
var sut=新装置(“123”,123);
sut.InitializeDeviceStatus();
//断言
mockConstructors.Verify();
}
具体的问题是如何模拟该行为:
servicepandable.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
    ...
}

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