在单元测试中对引发的事件抛出NullReferenceException的方法

时间:2018-08-02 13:39:10

标签: c# unit-testing moq nullreferenceexception

我正在使用Moq测试一个控制器,当我正在测试的方法引发一个事件时,我得到了NullReferenceException。关于如何解决这个问题的任何想法吗?

这是测试代码:

       //Arrange
        mockNumeriseur.Setup(x => x.InitialiserNumerisation());
        mockCommande.Setup(x => x.ConnaitreStatut()).Returns(numerisationReussie);
        mockNumeriseur.Setup(x => x.Numeriser(false, It.IsAny<string>(), It.IsAny<IntPtr>()));

        //Act
        controleur.Numeriser(new IntPtr(), false, false, false);

        //Assert
        mockNumeriseur.Verify(x => x.InitialiserNumerisation(), Times.Once());
        mockCommande.Verify(x => x.ConnaitreStatut(), Times.Once());
        mockNumeriseur.Verify(x => x.Numeriser(false, It.IsAny<string>(), It.IsAny<IntPtr>()), Times.Once());

这是导致问题的行:

ActiverBoutonsNumerisationUniqueEvent(this, new BooleanEventArgs(false));

BooleanEventArgs扩展了EventArgs以允许将布尔值传递给EventHandler。

编辑:我知道NullReferenceException是什么,我想弄清楚的是为什么触发此事件时单元测试会导致一个异常。我认为这可能与Unity / Moq有关,但是我是这些库的新手,所以我不知道从哪里开始。

1 个答案:

答案 0 :(得分:0)

感谢安东·帕夫洛夫(Anton Pavlov)的解决方案,我想将它发布在这里,以便在有人遇到相同问题时更加轻松。

使用null传播可解决此问题。基本上,它会在触发事件之前验证ActiverBoutonsNumerisationUniqueEvent是否为null。如果为null,则不会触发它。这是我测试的理想选择。

ActiverBoutonsNumerisationUniqueEvent?.Invoke(this, new BooleanEventArgs(false));