【问题标题】:Mocking inherited class with Moq用 Moq 模拟继承的类
【发布时间】:2011-08-08 14:37:33
【问题描述】:

我有一些我想为其编写单元测试的 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.");
}

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

【问题讨论】:

  • 你到底想测试什么?你为什么在模拟上调用 CreateWishListV1 ?我想这就是你要测试的方法?
  • 是的,我做错了。更新了问题;这样更好吗?

标签: c# inheritance methods moq


【解决方案1】:

在我的头顶:

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()中的代码。

【讨论】:

  • 有没有办法在不创建构造函数的情况下做到这一点?
  • 您可以公开Storage 属性,以便单元测试可以设置它。无论哪种方式 - 当您在对象中实例化依赖项时,您不能期望单元测试分配一个依赖项。
  • 是的,您可以通过属性注入 IStorage,或通过反射设置它。但是创建一个接受 IStorage 的构造函数将是恕我直言的最干净的方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-06-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-23
  • 1970-01-01
相关资源
最近更新 更多