2017-03-16 59 views
1

我剛開始使用moq對象進行單元測試,我不確定我是否正確執行此操作,請幫助!無法在單元測試中使用moq

Public Class Mrr: IMrr 
{ 

    public int Delete(double obj) 
    { 
     int rtcode = somefunction(obj);// retreiving some code from function 
     int DeleteMrr= DeleteFunction(rtcode); // delete function executes here   
     return 0; 
    } 

} 

這裏是接口

public interface IMrr 
{ 
    int Delete(double obj); 
} 

和我的測試方法是這樣的。

[TestMethod()] 
public void RetrieveSaveDeleteMRR() 
{  
    var FakeObject = new Moq.Mock<IMrr>(); 
    FakeObject.Setup(x => x.Delete(It.IsAny<int>())).Returns(0); 
    var Res = FakeObject.Object.Delete(10); 
} 

這不是要去執行該方法的實際功能,它假設去那裏的方法或不去。我不確定。

回答

1

如果你要測試Mrr.Delete()方法,你不應該模擬Mrr。您應該創建Mrr類的實例並調用其方法。

您通常想模擬Mrr依賴關係(在您的示例中沒有),以便不調用真正的依賴關係方法。

注意:您忘記從您的界面IMrr繼承Mrr

+0

HI, 我編輯我的代碼,你可以告訴我你是什麼人都在談論這裏真正的依賴? –

+0

請檢查Moq的基本教程 - http://deanhume.com/home/blogpost/basic-introduction-to-writing-unit-tests-with-moq/16 – CodeFuller

+0

是實現的必要接口嗎? –

1

在您的示例中,類Mrr沒有任何依賴關係。要解釋什麼是依賴關係,請看以下示例。

public class Mrr: IMrr 
{ 
    // This is dependency 
    IDelete _deleteObject; 

    public Mrr(IDelete deleteObject) 
    { 
     _deleteObject = deleteObject; 
    } 

    public int Delete(double obj) 
    { 
     int rtcode = somefunction(obj); 
     int DeleteMrr = _deleteObject.DeleteFunction(rtcode); 
     return 0; 
    } 
} 

public interface IDelete 
{ 
    int DeleteFunction(int rtcode); 
} 

這種依賴傳遞在構造函數,因此你可以在測試中提供自己的模擬實例。

比較這種情況:

public class Mrr: IMrr 
{ 
    // This is dependency 
    IDelete _deleteObject; 

    public Mrr() 
    { 
     _deleteObject = new DeleteClass(); 
    } 
} 

每次new使用它使不可能注入自己的實現在單元測試。

測試可能看起來像這樣。

[TestMethod] 
public void RetrieveSaveDeleteMRR() 
{  
    // Arange 
    int expected = 1; 
    Moq.Mock<IDelete> deleteObjectMock = new Moq.Mock<IDelete>(); 
    deleteObjectMock.Setup(x => x.DeleteFunction(It.IsAny<int>())).Returns(1000); 
    Mrr testedObject = new Mrr(deleteObjectMock.Object); 

    // Act 
    int actual = testedObject.Delete(10); 

    // Assert 
    Assert.AreEqual(expected, actual); 
}