测试正在通过,他们不应该

时间:2015-03-14 00:22:14

标签: asp.net-mvc-5 tdd mstest

之前我为每个控制器添加了[Authorize]个过滤器,我创建了测试用例并让它们通过。现在我已经在每个控制器的方法上添加了所述过滤器,但它们仍然通过,但我认为它们不应该是因为没有记录用户。我没有看到什么吗?

PS:我没有嘲笑身份2.0

修改:

基本上我通过工作单元模式嘲笑存储库。在我的单元测试中,我获得了对模拟存储库使用的List的引用,以便进行测试。

[TestMethod]
    public async Task CanCreateCustomerAndRedirectToDetails() {
        // Arrange
        Customer customer = NewCustomer(); // Gets a new customer that is NOT on the list
        CustomerCreateViewModel viewModel = Mapper.Map<CustomerCreateViewModel>(customer); // Maps to viewmodel

        // Act
        RedirectToRouteResult result = (RedirectToRouteResult) await Controller.Create(viewModel); // Sends to controller

        // Assert

        // Up to this point, Customers is the mock repository's list. so it should contain the new created customer since the controller should call the insert method
        // Normally, the assertion should pass. But after I implemented [Authorize] filter, I would expect the controller not to do anything (besides redirecting to login) and this test would fail
        Assert.IsNotNull(Customers.FirstOrDefault(e => e.ID == customer.ID));
        Assert.AreEqual("Details", result.RouteValues["action"].ToString());
    }

1 个答案:

答案 0 :(得分:1)

您的单元测试中没有任何内容可以响应或以任何方式检查Authorize属性。或任何属性。

属性实际上并未改变方法的行为。它们以其他代码(例如在ASP.NET MVC中的框架中)可能识别的方式来装饰该方法。 ASP.NET MVC框架使用Authorize属性。但是这个属性本身并没有改变方法。

MSTest没有使用Authorize属性。因此,如果您想测试它在方法上的存在,您需要以某种方式检查它。虽然这不应该是必要的。该供应商已对该框架的功能进行了全面测试。

您需要测试的所有测试都是该方法的功能。您不需要测试ASP.NET Framework的功能。

通过单元测试定义这些属性的类,可以非常有效地测试属性。例如,如果您创建了一个自定义属性(让我们称之为CustomAuthorize),那么您将拥有一个定义该属性的类(CustomAuthorizeAttribute),您可以单独测试该类从单元测试您的控制器。

相关问题