【发布时间】:2012-02-07 14:33:03
【问题描述】:
这个测试是为了检查我是否可以通过创建一个客户并调用 Details() 控制器方法来返回一个 ViewModel 对象。
[TestMethod()]
public void Can_View_AccountDetails()
{
AccountController target = new AccountController(null, null, null, null);
target.customer = new Customer { Id = 4, Active = true, BillingAddress_Id=1, ShippingAddress_Id=2 };
// Act
ActionResult result = target.Details();
// Assert
var resultData = ((ViewResult)result).ViewData.Model as AccountViewModel;
Assert.IsInstanceOfType(resultData, (typeof(AccountViewModel)));
}
'customer' 是控制器基类的成员,然后在 Initialize() 中分配。最初我不能给它分配任何东西,但是通过将它设置为“public”而不是“protected”,我能够在我的测试中使用它并且避免尝试调用基类 Initialize() 方法。
编辑:'customer' 是从注入基类构造函数的 Repository 对象填充的。
这是正确的方法吗?更改可访问性级别以使测试正常工作似乎有些错误。
另外,虽然我正在尝试使用 Moq 来创建我的测试,但我实际上并没有在这里进行任何模拟,这又似乎不对。
【问题讨论】:
-
AccountController 或基本控制器如何获取 Customer 实例/客户信息?
-
更新后:如何将客户/存储库注入基类而不注入 AccountController?你能显示那个代码吗?
标签: asp.net-mvc-3 unit-testing moq