簡體   English   中英

在單元測試中模擬班級中的班級

[英]Mock a Class in a Class in a Unit Test

我在單元測試中有以下代碼

using Moq;
using OtherClass;
[TestClass]
public class TestClass
{
    [TestMethod]
    public void TestMethod()
    {
        OtherClass other = new OtherClass();
        OtherClass.foo();
    }
}

這是另一堂課

using ThirdClass;
public class OtherClass
{
    public void foo()
    {
        ThirdClass third = new ThirdClass();
        third.bar();
    }
}

ThirdClass仍在開發中,但是我希望能夠使用moq來運行單元測試。 有沒有辦法告訴moq在TestClass內模擬ThirdClass,而不必讓OtherClass使用/依賴moq? 理想情況是:

public void TestMethod()
{
    OtherClass other = new OtherClass();
    Mock<ThirdClass> third =  new Mock<ThirdClass>();
    third.setup(o => o.bar()).Returns(/*mock implementation*/);
    /*use third in all instances of ThirdClass in OtherClass*/
    OtherClass.foo();
}

OtherClass方法foo()不可單元測試,因為您創建了真實服務的新實例,並且無法對其進行模擬。

如果要模擬它,則必須使用依賴項注入來注入ThirdClass

OtherClass示例將是:

public class OtherClass
{
    private readonly ThirdClass _thirdClass;
    public OtherClass(ThirdClass thirdClass) 
    {
         _thirdClass = thirdClass;
    }
    public void foo()
    {
        _thirdClass.bar();
    }
}

帶有測試其他類的示例的測試方法可以是:

public void TestMethod()
{
    // Arrange
    Mock<ThirdClass> third =  new Mock<ThirdClass>();
    third.setup(o => o.bar()).Returns(/*mock implementation*/);

    OtherClass testObject= new OtherClass(third);

    // Action
    testObject.foo();

    // Assert
    ///TODO: Add some assertion.
}

您可以對Unity DI容器使用示例嘗試。

謝謝你們的想法。 我最終制作了另一個版本的OtherClass.foo(),該版本采用ThirdClass的實例,而在沒有它的版本中創建實例。 測試時,我可以調用foo(mockThird),但是用戶可以只使用foo()。

using ThirdClass;
public class OtherClass
{
    public void foo(ThirdClass third)
    {
        third.bar();
    }
    public void foo()
    {
        foo(new ThirdClass());
    }
}

在測試班

public void TestMethod()
{
    Mock<ThirdClass> third =  new Mock<ThirdClass>();
    third.setup(o => o.bar()).Returns(/*mock implementation*/);
    OtherClass testObject= new OtherClass();

    testObject.foo(third);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM