2

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>> to Task<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?

pseudoramble
  • 2,541
  • 22
  • 28
  • I don't know if duplicate questions are visible or not to others searching. If they are though, the answer to this was that `result` contains two values - `Result` and `Value`, where `Result` is the original `ActionResult` and `Value` is of type `T`. So your test can use each of those properties to see what has happened. – pseudoramble Jan 17 '19 at 14:12
  • 1
    As the type is still relatively new I do not think much documentation about testing it has been done. I only found it because I look at the source code repository regularly. – Nkosi Jan 17 '19 at 14:16

0 Answers0