XUnit 测试 Web API 断言状态代码

sup*_*nja 4 c# api unit-testing xunit asp.net-core

我是XUnitWeb API 应用程序测试的新手。我试图用状态代码 404 断言我的响应值,但我不知道该怎么做。

这是我的测试代码。

假设输入为空,测试预计返回 NotFound 或 404 状态代码。

  [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?

        }
Run Code Online (Sandbox Code Playgroud)

在此测试方法的最后一行中,我无法进行response.StatusCode编译,因为响应变量没有StatusCode属性。而且没有HttpStatusCode我可以调用的类...

这是我GetBooksByID()在控制器类中的方法。

 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;
            }
        }
Run Code Online (Sandbox Code Playgroud)

谢谢!

Fab*_*bio 7

您可以检查返回的类型

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

// Assert
actualResult.Should().BeOfType<BadRequestResult>();
Run Code Online (Sandbox Code Playgroud)

Should()和是Fl​​uentAssertions.BeOfType<T>库中的方法,可在 Nuget 上使用

  • 我的错,我没有使用“using FluentAssertions;” (2认同)