使用异步方法上的Verifyable的UnitTest中的NullReferenceException [英] NullReferenceException in UnitTest using Verifyable on an async Method

查看:154
本文介绍了使用异步方法上的Verifyable的UnitTest中的NullReferenceException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是在使用xUnitMoq设置单元测试时遇到了问题.

I just had a problem with setting up a Unit Test using xUnit and Moq.

方法TestMethod()包含我要测试的逻辑.它是异步的,尽管返回Task

The Method TestMethod() contains the Logic, I want to test. It is async and though returns a Task

public class Testee
{
    private readonly IDoSomething _doSomething;

    public Testee(IDoSomething doSomething)
    {
        _doSomething = doSomething;
    }

    public async Task TestMethod()
    {
        await _doSomething.DoAsync(true); // throws NullReferenceException in Unit-Test
    }
}

界面IDoSomething看起来像这样

public interface IDoSomething
{
    Task DoAsync(bool aboolean);
}

单元测试

现在,我要像这样设置我的单元测试.

The Unit-Test

Now im Setting up my Unit-Test like this.

public class TesteeTest
{
    [Fact]
    public async Task MyTest()
    {
        var mock = new Mock<IDoSomething>();
        mock.Setup(x => x.DoAsync(It.IsAny<bool>())).Verifiable();

        var testee = new Testee(mock.Object);

        await testee.TestMethod(); // Test breaks here because it throws an exception

        mock.Verify(x => x.DoAsync(true), Times.Once);
        mock.Verify(x => x.DoAsync(false), Times.Never);
    }
}

为什么会出现此异常?

推荐答案

mock.Setup()缺少返回值并返回null.因此,在TestMethod()中,由_doSomething.DoAsync(true)返回的Tasknull. null等待着,当然会导致System.NullReferneceException.

The mock.Setup() is missing a return value and returns null. So in the TestMethod() the Task returned by _doSomething.DoAsync(true) is null. null gets awaited which of course results in a System.NullReferneceException.

要解决此问题,我建议将.Returns(Task.CompletedTask)添加到Mock-Setup中.

To Fix this, I'd recommend adding .Returns(Task.CompletedTask) to the Mock-Setup.

mock.Setup(x => x.DoAsync(It.IsAny<bool>())).Returns(Task.CompletedTask).Verifiable();

随着await使用Awaiter-Pattern进行编译,现在有一个任务可以调用.GetAwaiter()来返回TaskAwaiter.这些原则在这里有更好的解释:

As await gets compiled using the Awaiter-Pattern, there's now a Task to call .GetAwaiter() on it, to return a TaskAwaiter. These principles are better explained here:

  • dixin's Blog
  • Marko Papic's Blog

这篇关于使用异步方法上的Verifyable的UnitTest中的NullReferenceException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆