我目前正在单元测试,当发送无效的表单集合数据时会引发错误。
异常在 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)]
注释可以在这种情况下使用吗?