单元测试控制器中抛出的异常

时间:2013-02-13 14:38:52

标签: c# unit-testing exception asp.net-mvc-4

我目前正在进行单元测试,当发送无效的表单集合数据时会抛出错误。

异常是在HttpPost Index ActionResult方法中引发的,如下所示:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Index(FormCollection formCollection, PaymentType payType, string progCode)
    {
        ActionResult ar = redirectFromButtonData(formCollection, payType, progCode);

        if (ar != null)
        {
            return ar;
        }
        else
        {
            throw new Exception("Cannot redirect to payment form from cohort decision - Type:[" +  payType.ToString()  + "] Prog:[" +  Microsoft.Security.Application.Encoder.HtmlEncode(progCode) + "]");
        }
    }

到目前为止,我已经编写了一个成功命中异常的测试(我通过启用代码覆盖来验证这一点,我正在使用它来查看每个单独测试正在执行的代码)但是目前测试失败了因为我还没有至于已经定义了一种测试异常的方法,可以在下面找到该测试的代码:

    [TestMethod]
    public void Error_Is_Thrown_If_HVM_FormCollection_Data_Is_Incorrect()
    {
        var formCollection = new FormCollection();
        formCollection.Add("__RequestVerificationToken", "__RequestVerificationToken");
        formCollection.Add("invalid - invalid", "invalid- invalid");


        var payType = new PaymentType();
        payType = PaymentType.deposit;

        var progCode = "hvm";

        var mocks = new MockRepository();

        var httpRequest = mocks.DynamicMock<HttpRequestBase>();
        var httpContext = mocks.DynamicMock<HttpContextBase>();
        controller.ControllerContext = new ControllerContext(httpContext, new RouteData(), controller);
        mocks.ReplayAll();

        httpRequest.Expect(r => r.Url).Return(new Uri("http://localhost:8080/hvm/full/self/")).Repeat.Any();

        httpContext.Expect(c => c.Request).Return(httpRequest).Repeat.Any();

        var result = controller.Index(formCollection, payType, progCode);
    }

我已经看过使用[ExpectedException(typeof(Exception)]注释可以在这种情况下使用吗?

2 个答案:

答案 0 :(得分:2)

我冒昧地改变你的测试代码,略微符合rhino-mocks的最新功能。它不再需要创建MockRepository,您可以使用静态类MockRepository并调用GenerateMock<>。我还将你的SuT(被测系统)实例化低于你的模拟规范。

Nunit的例子(我对Nunit的体验比使用MSTest更好。主要是因为Nunit更频繁地发布并且具有更可靠的功能集。再次,不确定它是否适用于TFS但不应该很难找到)

[Test] // Nunit
[ExpectedException(typeof(Exception)) // NOTE: it's wise to throw specific 
// exceptions so that you prevent false-positives! (another "exception" 
// might make the test pass while it's a completely different scenario)
public void Error_Is_Thrown_If_HVM_FormCollection_Data_Is_Incorrect()
{
    var formCollection = new FormCollection();
    formCollection.Add("__RequestVerificationToken", "__RequestVerificationToken");
    formCollection.Add("invalid - invalid", "invalid- invalid");

    var payType = new PaymentType();
    payType = PaymentType.deposit;

    var progCode = "hvm";

    var httpRequest = MockRepository.GenerateMock<HttpRequestBase>();
    var httpContext = MockRepository.GenerateMock<HttpContextBase>();

    // define behaviour
    httpRequest.Expect(r => r.Url).Return(new Uri("http://localhost:8080/hvm/full/self/")).Repeat.Any();
    httpContext.Expect(c => c.Request).Return(httpRequest).Repeat.Any();

    // instantiate SuT (system under test)
    controller.ControllerContext = new ControllerContext(httpContext, new RouteData(), controller);

    // Test the stuff, and if nothing is thrown then the test fails
    var result = controller.Index(formCollection, payType, progCode);
}

与MStest几乎相同的处理,除了你需要更多的oldskool定义预期的异常。

[TestMethod] // MStest
public void Error_Is_Thrown_If_HVM_FormCollection_Data_Is_Incorrect()
{
    try
    {
        var formCollection = new FormCollection();
        formCollection.Add("__RequestVerificationToken", "__RequestVerificationToken");
        formCollection.Add("invalid - invalid", "invalid- invalid");

        var payType = new PaymentType();
        payType = PaymentType.deposit;

        var progCode = "hvm";

        var httpRequest = MockRepository.GenerateMock<HttpRequestBase>();
        var httpContext = MockRepository.GenerateMock<HttpContextBase>();

        // define behaviour
        httpRequest.Expect(r => r.Url).Return(new Uri("http://localhost:8080/hvm/full/self/")).Repeat.Any();
        httpContext.Expect(c => c.Request).Return(httpRequest).Repeat.Any();

        // instantiate SuT (system under test)
        controller.ControllerContext = new ControllerContext(httpContext, new RouteData(), controller);

        // Test the stuff, and if nothing is thrown then the test fails
        var result = controller.Index(formCollection, payType, progCode);
    }
    catch (Exception)
    {
        Assert.Pass();
    }
    Assert.Fail("Expected exception Exception, was not thrown");
}

如果您使用该部分,您可以通过提供的链接重构它以获得更好的可重用性:Assert exception from NUnit to MS TEST

答案 1 :(得分:0)

测试这个的最简单方法是将调用包装在try-catch中,并在执行catch块时设置一个布尔变量。类似的东西:

var exceptionIsThrown = false;
ActionResult result;
try 
{
    result = controller.Index(formCollection, payType, progCode);
}
catch(Exception)
{
    exceptionIsThrown = true;
}