gpt4 book ai didi

c# - 单元测试 Controller 中抛出的异常

转载 作者:行者123 更新时间:2023-11-30 17:07:04 26 4
gpt4 key购买 nike

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

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

最佳答案

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

Nunit 示例(与 MSTest 相比,我对 Nunit 的体验更好。主要是因为 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 .

关于c# - 单元测试 Controller 中抛出的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14855980/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com