等待模拟方法时单元测试中的 NRE

Cho*_*ard 3 c# unit-testing moq autofixture .net-core

我正在尝试使用 mstest 为 .net Core 3 Web API 构建单元测试。

我也在使用:

  • 自动夹具
  • 起订量
  • AutoFixture.AutoMoq

NotFound()当没有找到啤酒时,这个单元测试应该返回一个响应。

    private IFixture _fixture;
    private BeerController _beerController;
    private Mock<IBeerService> _mockBeerService;

    [TestInitialize]
    public void Initialize()
    {
        _fixture = new Fixture().Customize(new AutoMoqCustomization());
        _mockBeerService = _fixture.Freeze<Mock<IBeerService>>();
        _beerController = _fixture.Create<BeerController>();
    }

    [TestMethod]
    public async Task WhenCallGetBeerWithoutMatchReturnNotFound404()
    {
        //Arrange
        int beerId = _fixture.Create<int>();
        _mockBeerService.Setup(x => x.GetBeer(It.IsAny<int>())).Returns((Task<Beer>)null);

        //Act
        var actionResult = await _beerController.Get(beerId);

        //Assert
        Assert.IsInstanceOfType(actionResult.Result, typeof(NotFoundResult));
    }
Run Code Online (Sandbox Code Playgroud)

这就是我要测试的功能:

    [HttpGet("{beerId:int}")]
    public async Task<ActionResult<beer>> Get(int beerId)
    {
        try
        {
            var beer = await _beerService.Getbeer(beerId);
            if (beer == null) return NotFound();

            return Ok(beer);
        }
        catch (Exception)
        {
            return BadRequest();
        }
    }
Run Code Online (Sandbox Code Playgroud)

但是我Object reference not set to an instance of an object.在这行代码中遇到了异常:var beer = await _biereService.Getbeer(beerId);

这是堆栈跟踪: at BeerProject.Controllers.BeerController.<Get>d__2.MoveNext() in F:\DevProjects\Repos\API_BeerProject\BeerProject\Controllers\BeerController.cs:line 29

return Ok(beer)用这个测试进行了测试:

    [TestMethod]
    public async Task WhenCallGetBeerWithMatchReturnOk200()
    {
        //Arrange
        int beerId = _fixture.Create<int>();
        var beer = _fixture.Create<Task<Beer>>();

        _mockBeerService.Setup(x => x.GetBeer(It.IsAny<int>())).Returns(beer);
        //Act
        var actionResult = await _beerController.Get(beerId);

        //Assert
        Assert.IsInstanceOfType(actionResult.Result, typeof(OkObjectResult));
    }  
Run Code Online (Sandbox Code Playgroud)

它工作正常。

所以我猜测,他不喜欢.Returns((Task<Beer>)null)WhenCallGetBeerWithoutMatchReturnNotFound404()

yaa*_*kov 5

在您的控制器中,您假设GetBeer返回一个非空任务,因为您无条件地等待它。然后你检查结果,啤酒,看看它是null不是:

var beer = await _beerService.Getbeer(beerId);
if (beer == null) return NotFound();
Run Code Online (Sandbox Code Playgroud)

在这一行中,您不是返回带有null啤酒的任务,而是返回一个null任务:

_mockBeerService.Setup(x => x.GetBeer(It.IsAny<int>())).Returns((Task<Beer>)null);
Run Code Online (Sandbox Code Playgroud)

因此,等待null导致您的NullReferenceException.

如果您想null作为任务的结果返回啤酒,则需要使用:

_mockBeerService.Setup(x => x.GetBeer(It.IsAny<int>())).Returns(Task.FromResult<Beer>(null));
Run Code Online (Sandbox Code Playgroud)

甚至:

_mockBeerService.Setup(x => x.GetBeer(It.IsAny<int>())).ReturnsAsync(null);
Run Code Online (Sandbox Code Playgroud)