3

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

异常在 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)]注释可以在这种情况下使用吗?

4

2 回答 2

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 的处理几乎相同,只是您需要将预期的异常定义得更老一些。

[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

于 2013-02-13T14:56:54.717 回答
0

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

var exceptionIsThrown = false;
ActionResult result;
try 
{
    result = controller.Index(formCollection, payType, progCode);
}
catch(Exception)
{
    exceptionIsThrown = true;
}
于 2013-02-13T15:01:33.110 回答