在过去,我只使用 Rhino Mocks,具有典型的严格模拟.我现在正在与 Moq 合作开展一个项目,我想知道如何正确使用.
In the past, I have only used Rhino Mocks, with the typical strict mock. I am now working with Moq on a project and I am wondering about the proper usage.
假设我有一个带有方法 Bar 的对象 Foo,它在对象 Buzz 上调用 Bizz 方法.
Let's assume that I have an object Foo with method Bar which calls a Bizz method on object Buzz.
在我的测试中,我想验证是否调用了 Bizz,因此我觉得有两种可能的选择:
In my test, I want to verify that Bizz is called, therefore I feel there are two possible options:
严格的模拟
var mockBuzz= new Mock<IBuzz>(MockBehavior.Strict);
mockBuzz.Setup(x => x.Bizz()); //test will fail if Bizz method not called
foo.Buzz = mockBuzz
foo.Bar();
mockBuzz.VerifyAll();
使用松散的模拟
var mockBuzz= new Mock<IBuzz>();
foo.Buzz = mockBuzz
foo.Bar();
mockBuzz.Verify(x => x.Bizz()) //test will fail if Bizz method not called
是否有标准或正常的方式来做这件事?
Is there a standard or normal way of doing this?
当我第一次在单元测试中开始使用 mock 时,我曾经使用严格的 mock.这并没有持续很长时间.我停止这样做的真正原因有两个:
I used to use strict mocks when I first starting using mocks in unit tests. This didn't last very long. There are really 2 reasons why I stopped doing this:
因此,我强烈建议您在单元测试中使用松散的模拟.
Because of these I would strongly recommend using loose mocks in your unit tests.
这篇关于起订量,严格与宽松使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!