用Moq嘲弄继承类

本文关键字:继承 嘲弄 Moq | 更新日期: 2023-09-27 17:50:37

我有一些Web API方法,我想为它们编写单元测试。他们需要数据库访问,所以,很自然地,我想Moq那部分。

通过接口访问存储类,实现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.");
}

必须更改APIAccess上的Storage属性为public

用Moq嘲弄继承类

Off the top of my head:

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

然后用自己的构造函数创建CreateWishList对象,接受IStorage

var createWishList = new CreateWishList(storage.Object);  

要对CreateWishList()方法进行单元测试,您需要编写一个单独的测试。这个测试应该纯粹用来检查CreateWishListV1()中的代码。