【问题标题】:Method throwing NullReferenceException on raised event in unit test在单元测试中引发的事件上抛出 NullReferenceException 的方法
【发布时间】:2018-08-02 13:39:09
【问题描述】:

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

【问题讨论】:

  • 您可以在调试模式下运行单元测试。
  • ActiverBoutonsNumerisationUniqueEvent 会发生什么?
  • 我在测试中没有看到此活动的任何作业,您确定有吗?并且在所有情况下都使用空传播来避免这种异常:ActiverBoutonsNumerisationUniqueEvent?.Invoke(this, new BooleanEventArgs(false));
  • 测试并不是要验证事件是否被触发,而是要验证两个类中的方法是否被正确调用。 ActiverBoutonsNumerisationUniqueEvent 在扫描开始或完成时更新视图。我知道我可以在调试模式下运行单元测试,这就是我发现这条线导致 NullReferenceException 的原因。我的代码在正常情况下运行良好,当我运行测试时它崩溃了。

标签: c# unit-testing moq nullreferenceexception


【解决方案1】:

感谢 Anton Pavlov 提供的解决方案,如果有人遇到同样的问题,我想我会在此处发布以方便使用。

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

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

【讨论】:

    猜你喜欢
    • 2011-05-09
    • 1970-01-01
    • 1970-01-01
    • 2010-09-19
    • 2011-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多