I noticed that ASP.NET Core controllers, when returning status codes for requests, can return NotFound() for a 404, or Ok() for a 200, which are StatusCodeResult objects. Here’s an example controller function that does so:
public ActionResult<MyItem> GetItemById(int ItemId) {
var item = _service.GetItemById(ItemId);
if (item is null) {
return NotFound();
}
return item;
}
When I write a unit test for this controller’s GetItemById function, and I want to test if it returns a 404 when there is no item with that ItemId, I currently write the following unit test (I’m using xUnit in this example):
[Fact]
public void TestGetItemByIdNotFound() {
var response = controller.GetItemById(1); // no item with ItemId 1
var result = Assert.IsType<NotFoundResult>(response);
Assert.Equal(404,result!.StatusCode);
}
In my test, I’m comparing the integer 404 with the status code of the result. I would prefer to reference something similar to NotFound() instead of a number in my test so that I don’t have to memorize the status code for every StatusCodeResult that my controller will return, and just have something with similar syntax in my assertion. Is there a way to do so?
So far, I’ve just made an enumerator of different status codes and their returns, then referenced those in my test:
enum StatusCodes {
Ok = 200,
NotFound = 404,
...
}
...
Assert.Equal((int)StatusCodes.NotFound, result!.StatusCode)
But I’m curious if there’s a cleaner way that leaves me without having to enumerate every possible status code.
>Solution :
As in documents if the Item is not found. For this case, the unit test just checks if the return type is NotFoundResult, you don’t need to manually check for the status code because we already check the type which ensure that status code will be 404.
moreover like @Martin mention status codes alredy defend in System.Net.HttpStatusCode