繁体   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