简体   繁体   English

在 Assert.Multiple 中验证模拟

[英]Verify mocks in Assert.Multiple

Is it possible to verify a method call in an Assert.Multiple block alongside other calls to Assert ?是否可以在Assert.Multiple块中验证方法调用以及对Assert的其他调用?

My current solution does not call the assert on SomeProperty , when the method call to MyMethod does not verify.当对MyMethod的方法调用未验证时,我当前的解决方案不会调用SomeProperty上的断言。 And the only way to get close to what I want would be to move the call to myInterfaceMock.Verify to the end, but that does no longer work when there are multiple method calls to verify.接近我想要的唯一方法是将调用myInterfaceMock.Verify移到最后,但是当有多个方法调用需要验证时,这不再起作用。

var mInterfaceMock = new Mock<IMyInterface>()
  .Setup(x => x.MyMethod())
  .Verifiable();
var systemUnderTest = new MyClass(myInterfaceMock.Object);

systemUnderTest.MethodToTest();

Assert.Multiple(() => {
  myInterfaceMock.Verify();
  Assert.That(systemUnderTest.SomeProperty, Is.True);
});

The verify will throw its own exception that the assertion block wont know how to handle.验证将抛出它自己的异常,断言块不知道如何处理。 That is why when the verify fails nothing gets invoked after it.这就是为什么当验证失败时,在它之后什么都不会被调用。

The notes in documentation also states文档中的注释还指出

The test will be terminated immediately if any exception is thrown that is not handled.如果抛出任何未处理的异常,测试将立即终止。 An unexpected exception is often an indication that the test itself is in error, so it must be terminated.意外的异常通常表明测试本身有错误,因此必须终止它。 If the exception occurs after one or more assertion failures have been recorded, those failures will be reported along with the terminating exception itself.如果在记录一个或多个断言失败之后发生异常,则这些失败将与终止异常本身一起报告。

Reference Multiple Asserts引用多个断言

Consider the following approach考虑以下方法

//...

Assert.Multiple(() => {
  Assert.That(() => myInterfaceMock.Verify(), Throws.Nothing);
  Assert.That(systemUnderTest.SomeProperty, Is.True);
});

If the verify throws an exception then it will be handled by its own assertion.如果验证抛出异常,那么它将由它自己的断言处理。

If your MethodToTest() does not return anything they I'd recommend just verifying if the method run, as you're trying to do with the assert, but I'd recommend doing something like this:如果您的MethodToTest()没有返回任何内容,我建议您仅验证该方法是否运行,就像您尝试使用断言一样,但我建议您执行以下操作:

mInterfaceMock.Verify(x => x.MethodToTest(), Times.Once);

just specifying the times it has had to run, without it inside of an assertion只是指定它必须运行的时间,没有它在断言中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM