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

Method throwing NullReferenceException on raised event in unit test

我正在使用 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 有关,但我是这些库的新手,所以我不知道从哪里开始。

感谢 Anton Pavlov 提供的解决方案,我想我 post 在这里可以让遇到同样问题的人更容易解决。

使用空值传播解决了这个问题。基本上它会在触发事件之前验证 ActiverBoutonsNumerisationUniqueEvent 是否为 null。如果它为 null,则不会触发它。这非常适合我的测试。

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