gpt4 book ai didi

c# - 我想检查单元测试是否抛出了正确的业务异常?

转载 作者:太空宇宙 更新时间:2023-11-03 19:43:40 25 4
gpt4 key购买 nike

这是我在 Controller 中的方法。

public ActionResult DeleteModelAliasData(string alias)
{
if (!ModelState.IsValid)
{
ModelState.LogModelStateError();
throw new BusinessException("COMMON_ERROR");
}

var response = _vehicleDataBusinessService.DeleteModelAliasData(alias);
return Json(response);
}

我是单元测试的新手,我想编写单元测试,当“!ModelState.IsValid”抛出异常时,我想检查它是否是正确的异常我想要?

最佳答案

您可以按照下面的代码执行相同的操作。

 var ex = Assert.Throws<BusinessException>(() => controller.DeleteModelAliasData(alias));
Assert.That(ex.Message, Is.EqualTo("COMMON_ERROR"));

引用: NUnit Exception Asserts


更新:

[Test]
public void TestDeleteModelAliasData()
{
// Get your controller instance - you know it better how to instantiate
var controller = GetControllerInstance();

// Add error message to ModelState
controller.ModelState.AddModelError("PropertyName", "Error Message");

var alias = "sampleAlias";

// As ModelState is having an Error, the method should throw BusinessException
var ex = Assert.Throws<BusinessException>(() => controller.DeleteModelAliasData(alias));

// Exception is raised, assert the message if you want
Assert.That(ex.Message, Is.EqualTo("COMMON_ERROR"));
}

关于c# - 我想检查单元测试是否抛出了正确的业务异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49292447/

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