簡體   English   中英

用Moq模擬繼承的類

[英]Mocking inherited class with Moq

我有一些要為其編寫單元測試的Web API方法。 他們需要數據庫訪問權限,因此,自然地,我想起那一部分。

可通過接口訪問存儲類,而實現API方法的類將繼承該接口。 我不知道如何模擬單元測試中的繼承接口。

public class CreateWishList : APIAccess
{
    public long CreateWishListV1(long userId, string wishListName)
    {
        // Do stuff like
        long result = Storage.CreateWishList(userId, wishListName);

        return result;
    }
}

public class APIAccess
{
    protected IStorage Storage { get; private set; }

    public APIAccess() : this(new APIStorage()) { }

    public APIAccess(IStorage storage)
    {
        Storage = storage;
    }
}

public interface IStorage
{
    long CreateWishList(long userId, string wishListName);
}

因此,我想對CreateWishListV1(...)方法進行單元測試,並且在沒有數據庫訪問權限的情況下進行此操作,我需要模擬Storage.CreateWishList(...)返回的內容。 我怎么做?

更新:

我正在嘗試這樣的事情:

[Test]
public void CreateWishListTest()
{
    var mockAccess = new Mock<APIAccess>(MockBehavior.Strict);
    mockAccess.Setup(m => m.Device.CreateWishList(It.IsAny<long>(), It.IsAny<string>())).Returns(123);

    var method = new CreateWishList();
    method.Storage = mockAccess.Object;

    long response = method.CreateWishListV1(12345, "test");

    Assert.IsTrue(response == 123, "WishList wasn't created.");
}

還必須將APIAccessStorage屬性也APIAccess為public。

從我的頭頂上:

var storage = new Mock<IStorage>();
storage.Setup(x => x.CreateWishList(It.IsAny<long>(), It.IsAny<string>())
       .Returns(10);

然后使用自己的接受IStorage的構造函數創建CreateWishList對象。

var createWishList = new CreateWishList(storage.Object);  

要對CreateWishList()方法進行單元測試,您將編寫一個單獨的測試。 該測試應僅通過檢查CreateWishListV1()的代碼來完成。

暫無
暫無

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

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