2016-01-11 51 views
1

我一直在經歷Moq的plural sight教程。使用安排,行爲,斷言的AAA校長,我已經成功地嘲笑了一個名爲GetDeviceSettingsForSerialNumber設置一個moq來模擬一個複雜類型使用It.IsAny

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

但是方法,嘲諷一個稍微複雜的類型對我來說太難了,在這一點上,和我尋求你的指導。

,我測試看起來像這樣的代碼:

enter image description here

我已經開始了嘗試下面的測試沒有運氣:

[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方法?

+0

爲了能夠回答你的問題,我需要知道'GetPatientDeviceStatus'的簽名。順便說一句,你不能使用moq來模擬C'tor,你必須做一些重構才能使用moq來測試'InitializeDeviceStatus'。請添加'GetPatientDeviceStatus'的簽名,然後我可以發佈完整的詳細答案。 –

回答

1

查看方法InitializeDeviceStatusnew關鍵字的使用位置。這裏因爲使用了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 
    ... 
} 
相關問題