【发布时间】: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