gpt4 book ai didi

c# - 如何对 Web API 中冲突响应的错误消息进行单元测试

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

这是我的端点:

public IHttpActionResult Work()
{
try
{
this.Service.DoWork();
return this.Ok();
}
catch (SomeException)
{
return this.Content(HttpStatusCode.Conflict, new { Message = "The message" });
}
}

如何对错误消息进行单元测试?

这是一个测试模板:

[Test]
public void Work_Conflict()
{
this.Service.Setup(x => x.DoWork()).Throws<SomeException>();
var result = (<what goes here?>)this.MyController.Work();
Assert.AreEqual("The message", <what goes here?>);
}

最佳答案

你快到了。

您需要将结果转换为从 ApiController 返回的实际类型并提取预期数据。

[Test]
public void Work_Conflict()
{
this.Service.Setup(x => x.DoWork()).Throws<SomeException>();
IHttpActionResult result = this.MyController.Work();
var objectResult = result as ObjectResult;
Assert.IsNotNull(objectResult);
dynamic model = objectResult.Value;
string actual = (string)model.Message;
string expected = "The message";
Assert.AreEqual(expected, actual);
}

关于c# - 如何对 Web API 中冲突响应的错误消息进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58751969/

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