I am trying to build a unit test around a controller using .NET Core's Web API. I'm running into an issue when creating a test for a negative scenario where the response should be a BadRequest(string)
:
ThingController.cs
[HttpPost("thing/{id}")]
[ProducesResponseType(400)]
public async Task<ActionResult<Thing>> Add(string id, [FromBody] Thing thing)
{
if (String.IsNullOrEmpty(id))
{
return BadRequest("Must provide Thing ID");
}
return this.thingRepo.AddThing(id, thing);
}
ThingControllerTests.cs
[Test]
public async Task AddThing_FailOnEmptyId() {
var mockRepo = new Mock<IThingRepository>();
var testController = new ThingController(mockRepo.Object);
var result = await testController.AddThing("", this.validThing);
Assert.That(result, Is.InstanceOf<BadRequestObjectResult>());
}
In this case, the value of result
is always Thing
where I expect it to be BadRequestObjectResult
.
Some additional details:
- I've verified that the test exercises the correct branch and performs
return BadRequest("Must provide Thing ID")
like I expected. - If I change the return type from
Task<ActionResult<T>>
toTask<ActionResult>
the test passes like I expect. - After reading the docs on the Microsoft site Controller action return types - ActionResult T type I think I have the code itself correct enough for this test.
Is there a specific cast I need to perform to get the proper type? Am I missing a detail about NUnit that will make this work?