C# 如何测试在try/catch中捕获异常后Api是否返回特定消息
我正在用xunit编写一个测试方法。因此,当用户注册失败时,catch块中会返回一条特定消息。在测试方法中,我想检查是否返回了正确的消息。但当我跑步时,我会收到以下信息:C# 如何测试在try/catch中捕获异常后Api是否返回特定消息,c#,C#,我正在用xunit编写一个测试方法。因此,当用户注册失败时,catch块中会返回一条特定消息。在测试方法中,我想检查是否返回了正确的消息。但当我跑步时,我会收到以下信息: EnrollUser failed with HTTP response code:BadRequest. 如果有人能帮我找到,如果可能的话,如何检索我想要的消息。 下面是代码 public async Task<IHttpActionResult> EnrollUser([FromUri]int id, int
EnrollUser failed with HTTP response code:BadRequest.
如果有人能帮我找到,如果可能的话,如何检索我想要的消息。
下面是代码
public async Task<IHttpActionResult> EnrollUser([FromUri]int id, int userId, int?
organizationId = null)
{
try
{
if (organizationId.HasValue)
{
Do something.....
}
else
{
Do something.....
}
return Ok();
}
catch (Exception e)
{
var errorMsg = $"User enrollment failed for userId:{userId}, serviceId:{id}.";
return (IHttpActionResult)BadRequest(errorMsg);
}
}
[Fact]
public async Task EnrollUser_Should_Return_Failure_Message()
{
const int userId = 2310;
const int serviceId = 9;
const string expectedMessage = "User enrollment failed for userId:{userId}, serviceId:{id}.";
Func<Task> act = () => EnrollUser(userId, serviceId);
var actualException = await Assert.ThrowsAsync<Exception>(act);
Assert.Equal(expectedMessage, actualException.Message);
}
public异步任务注册用户([FromUri]int-id,int-userId,int?
organizationId=null)
{
尝试
{
if(organizationId.HasValue)
{
做点什么。。。。。
}
其他的
{
做点什么。。。。。
}
返回Ok();
}
捕获(例外e)
{
var errorMsg=$“userId:{userId},serviceId:{id}的用户注册失败。”;
返回(IHttpActionResult)错误请求(errorMsg);
}
}
[事实]
公共异步任务注册用户\u应\u返回\u失败\u消息()
{
const int userId=2310;
const int serviceId=9;
const string expectedMessage=“userId:{userId},serviceId:{id}的用户注册失败。”;
Func act=()=>EnrollUser(用户ID、服务ID);
var actualException=await Assert.ThrowsAsync(act);
相等(expectedMessage、actualException.Message);
}
异常在EnrollUser
方法中处理,因此此方法不会引发异常,它将返回BadRequest对象,您可以使用该对象来比较消息
var result = await act;
Assert.Equal(expectedMessage, act.Request);