Here is my endpoint:
public IHttpActionResult Work()
{
try
{
this.Service.DoWork();
return this.Ok();
}
catch (SomeException)
{
return this.Content(HttpStatusCode.Conflict, new { Message = "The message" });
}
}
How can I unit test the error message?
Here is a test template:
[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?>);
}
You were almost there.
You need to cast the result to the actual types returned from the ApiController and extract the expected data.
[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);
}
Try this: where BadRequestObjectResult comes from the Microsoft.AspNetCore.Mvc namespace
public void Work_Conflict()
{
//Arrange
this.Service.Setup(x => x.DoWork()).Throws<SomeException>();
using (var controller = new MyController()) ;
//Act
var result = MyController.Work();
var badRequest = result as BadRequestObjectResult;
//Assert
var conflictCode = 0;
Assert.AreEqual(conflictCode, badRequest.StatusCode);
Assert.AreEqual("The message", badRequest.Value);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.