我读过各种关于测试中模仿和存根的文章,包括Martin Fowler的《Mocks Aren't Stubs》,但我仍然不理解其中的区别。


当前回答

上面有很多有效的答案,但我认为值得一提的是这个表格鲍勃叔叔: https://8thlight.com/blog/uncle-bob/2014/05/14/TheLittleMocker.html

最好的例子解释!

其他回答

他使用的通用术语是测试替身(想想特技替身)。Test Double是一个通用术语,用于为测试目的替换生产对象的任何情况。杰拉德列出了各种各样的替身:

Dummy objects are passed around but never actually used. Usually they are just used to fill parameter lists. Fake objects actually have working implementations, but usually take some shortcut which makes them not suitable for production (an InMemoryTestDatabase is a good example). Stubs provide canned answers to calls made during the test, usually not responding at all to anything outside what's programmed in for the test. Spies are stubs that also record some information based on how they were called. One form of this might be an email service that records how many messages it was sent(also called Partial Mock). Mocks are pre-programmed with expectations which form a specification of the calls they are expected to receive. They can throw an exception if they receive a call they don't expect and are checked during verification to ensure they got all the calls they were expecting.

存根用于您在测试中设置的具有预期返回值的方法。 mock用于void方法,这些方法在调用时的Assert中进行验证。

存根和模拟都覆盖外部依赖项,但区别在于

stub ->用于测试数据

mock ->用于测试行为


不测试任何东西(只是用空方法覆盖功能,例如替换Logger以避免在测试时记录任何噪音)

Stub帮助我们运行测试。怎么做?它给出了有助于运行测试的值。这些值本身不是真实的,我们创建这些值只是为了运行测试。例如,我们创建一个HashMap来提供与数据库表中的值相似的值。因此,我们不直接与数据库交互,而是与Hashmap交互。

Mock是一个运行测试的伪对象。我们在这里输入assert。

非常清楚和实际:

Stub:实现要伪造的类/对象的方法的类或对象,并且总是返回你想要的东西。

JavaScript示例:

var Stub = {
   method_a: function(param_a, param_b){
      return 'This is an static result';
   }
}

Mock:与存根相同,但是它增加了一些逻辑,当一个方法被调用时“验证”,这样你就可以确定某个实现正在调用该方法。

正如@mLevan所说,假设你正在测试一个用户注册类。在调用Save之后,它应该调用SendConfirmationEmail。

一个非常愚蠢的代码

var Mock = {
   calls: {
      method_a: 0
   }

   method_a: function(param_a, param_b){
     this.method_a++; 
     console.log('Mock.method_a its been called!');
   }
}