最小起订量重新抛出错误传递到安装程序

Lia*_*iam 1 c# nunit unit-testing moq

所以我有一个使用该接口的错误处理类:

public interface IEventLogger
  {
    void WriteError(Exception ex, string message);
  }
Run Code Online (Sandbox Code Playgroud)

所以我用Moq来模拟这个以进行单元测试。此方法通常只会将错误记录到事件查看器中,但对于我的单元测试,我希望它重新抛出传递到该方法中的异常,即,如果将错误传递到此模拟类中,我希望单元测试失败。我有什么想法可以做到这一点吗?

我到目前为止:

 var moqIEventLogger = new Mock<IEventLogger>();
 moqIEventLogger.Setup(s => s.WriteError(It.IsAny<Exception>(), 
                                           It.IsAny<string>()));
Run Code Online (Sandbox Code Playgroud)

但我不确定如何访问原始异常(如果可能的话)?

Raf*_*fal 5

如果你只想让它失败,那么使用Throws如下方法:

moqIEventLogger
            .Setup(s => s.WriteError(It.IsAny<Exception>(),It.IsAny<string>()))
            .Throws<InvalidOperationException>();
Run Code Online (Sandbox Code Playgroud)

如果你希望它抛出作为参数的异常,请尝试:

moqIEventLogger
            .Setup(s => s.WriteError(It.IsAny<Exception>(),It.IsAny<string>()))
            .Callback((Exception ex, string s) => { throw ex; });
Run Code Online (Sandbox Code Playgroud)