【问题标题】:Unit testing Controller method - assign value to base class property to avoid using Initialize()单元测试控制器方法 - 为基类属性赋值以避免使用 Initialize()
【发布时间】: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


【解决方案1】:

我认为您真正的问题是客户信息“神奇地”显示在AccountController 中。 Customer 实例应该从外部注入到 AccountController 中,因为它是一个外部依赖项。在这种情况下,您不必公开 customer 属性,因为您自己将其传递给 AccountController

【讨论】:

    【解决方案2】:

    受保护意味着它只能从派生类访问,因此测试类需要继承受保护类。

    您也将其视为最小起订量,但我没有看到任何模拟测试。您应该使用代表 Customer 类的接口,以便您可以模拟 ICustomer 接口。

    【讨论】:

      【解决方案3】:

      您需要存根您的 Repository 对象并对其进行设置,以便它返回客户。然后,您不需要将.customer 属性公开为public(或internal)——您只需告诉存储库存根返回您想要的那个:

      var repositoryStub = new Mock<IRepository>();
      var customer = new Customer { /* ... */ };
      repositoryStub.Setup(r => r.GetCustomer()).Returns(customer);
      

      当然,您需要初始化您的 AccountContoller 并使用对存储库的存根依赖(以及其他依赖,如果需要):

      var accountController = new AccountController(repositoryStub, ...);
      

      这当然假设您的 AccountController 可以依赖存储库。

      所以现在,当您在基类上调用 Initialize() 时,它应该使用存根存储库并将您的私有 .customer 字段设置为您在存根设置期间指定它返回的字段。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-04-01
        • 1970-01-01
        • 2012-04-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-08-05
        相关资源
        最近更新 更多