Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XUnit Test Web API Assert Status code

I am new in XUnit tests for Web API application. I am trying to make assertion of my response value with the status code 404, but I am not sure how to do so.

Here's my test code.

Assume the input is null, the test is expected to return NotFound or 404 status code.

  [Fact]
        public async Task getBooksById_NullInput_Notfound()
        {

            //Arrange
            var mockConfig = new Mock<IConfiguration>();
            var controller = new BookController(mockConfig.Object);

            //Act
            var response = await controller.GetBooksById(null);

            //Assert
            mockConfig.VerifyAll();

            Assert(response.StatusCode, HttpStatusCode.NotFound()); //How to achieve this?

        }

In the last line of this test method, I am not able to make response.StatusCode compile as in the response variable does not have StatusCode property. And there is no HttpStatusCode class that I can call...

Here's my GetBooksByID() method in the controller class.

 public class BookController : Controller
    {
        private RepositoryFactory _repositoryFactory = new RepositoryFactory();

        private IConfiguration _configuration;

        public BookController(IConfiguration configuration)
        {
            _configuration = configuration;
        }



        [HttpGet]
        [Route("api/v1/Books/{id}")]
        public async Task<IActionResult> GetBooksById(string id)
        {
            try
            {
                if (string.IsNullOrEmpty(id))
                {
                    return BadRequest();
                }

                var response = //bla

                //do something

                if (response == null)
                {
                    return NotFound();
                }
                return new ObjectResult(response);
            }
            catch (Exception e)
            {
                throw;
            }
        }

Thanks!

like image 960
superninja Avatar asked Sep 09 '26 06:09

superninja


1 Answers

You can check against returned type

// Act
var actualResult = await controller.GetBooksById(null);

// Assert
actualResult.Should().BeOfType<BadRequestResult>();

Should() and .BeOfType<T> are methods from FluentAssertions library, which available on Nuget

like image 86
Fabio Avatar answered Sep 10 '26 20:09

Fabio