C# 在单元测试中引发的事件上引发NullReferenceException的方法

C# 在单元测试中引发的事件上引发NullReferenceException的方法,c#,unit-testing,moq,nullreferenceexception,C#,Unit Testing,Moq,Nullreferenceexception,我正在使用Moq测试一个控制器,当我正在测试的方法引发事件时,我会得到一个NullReferenceException。有没有办法解决这个问题 以下是测试代码: //Arrange mockNumeriseur.Setup(x => x.InitialiserNumerisation()); mockCommande.Setup(x => x.ConnaitreStatut()).Returns(numerisationReussie);

我正在使用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());
BooleanEventArgs扩展了EventArgs,允许将布尔值传递给EventHandler


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

多亏了安东·巴甫洛夫的解决方案,我想我会把它贴在这里,以便在有人遇到同样的问题时更容易处理

使用null传播修复了这个问题。基本上,它会在触发事件之前验证ActiveRBoutonNumerisationUniqueEvent是否为null。如果为空,则不会触发它。这是我测试的理想选择

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

您可以在调试模式下运行单元测试。在
ActiveRBoontNumerisationUniqueEvent
中会发生什么?我在测试中没有看到任何对此事件的分配,您确定有分配吗?并且在所有情况下都使用null传播来避免此类异常:ActiveRBoutOnNumerisationUniqueEvent?.Invoke(这是新的BooleanEventArgs(false));测试的可能重复并不意味着验证是否触发了事件,而是验证是否为正确的情况调用了两个类中的方法。当扫描开始或完成时,ActiverButtonSumberisationUniqueEvent更新视图。我知道我可以在调试模式下运行单元测试,这就是我发现这行代码导致NullReferenceException的原因。我的代码在正常情况下工作正常,只有在运行测试时才会崩溃。
ActiverBoutonsNumerisationUniqueEvent?.Invoke(this, new BooleanEventArgs(false));