【发布时间】: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