Unit Testing .NET Core 2 Web Api
Full source code available here.
Unit testing Web API controllers in .NET Core 2 is very easy.
I have very simple GET
and POST
methods.
1[Route("api/[controller]")]
2public class ValuesController : Controller
3{
4 [HttpGet]
5 public async Task<IActionResult> Get()
6 {
7 // imagine some db logic
8 List<string> values = new List<string>() { "value1", "value2" };
9 return Ok(values);
10 }
11
12 [HttpPost]
13 public async Task<IActionResult> Post([FromBody]string value)
14 {
15 // imagine some db logic
16 return Created("", value);
17 }
18}
Add an xUnit Test Project to your solution.
In the test project add a ValuesControllerTests
class.
Add a method to test the ValuesController.Get
like this -
1[Fact]
2public async Task TestGet()
3{
4 // Arrange
5 var controller = new ValuesController();
6
7 // Act
8 IActionResult actionResult = await controller.Get();
9
10 // Assert
11 Assert.NotNull(actionResult);
12
13 OkObjectResult result = actionResult as OkObjectResult;
14
15 Assert.NotNull(result);
16
17 List<string> messages = result.Value as List<string>;
18
19 Assert.Equal(2, messages.Count);
20 Assert.Equal("value1", messages[0]);
21 Assert.Equal("value2", messages[1]);
22}
Note here how I expect the result to be an OkObjectResult
OkObjectResult result = actionResult as OkObjectResult;
And here where I cast the result.Value
as List
, the type I sent from the controller. No deserializing from json, strings or byte arrays needed!
List<string> messages = result.Value as List<string>;
Now it is simple to perform the appropriate asserts.
Here is another example, this time testing the ValuesController.Post()
.
1[Fact]
2public async Task TestPost()
3{
4 // Arrange
5 var controller = new ValuesController();
6
7 // Act
8 IActionResult actionResult = await controller.Post("Some value");
9
10 // Assert
11 Assert.NotNull(actionResult);
12 CreatedResult result = actionResult as CreatedResult;
13
14 Assert.NotNull(result);
15 Assert.Equal(201, result.StatusCode);
16}
You can also test a result for NotFoundResult
, OkResult
, UnauthorizedResult
, etc.
Full source code available here.