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


当前回答

模拟:帮助模拟和检查结果交互。这些交互 SUT调用它的依赖项来改变它们的状态。

存根:帮助模拟传入的交互。这些相互作用称为 SUT对其依赖项进行处理以获取输入数据。

来源:单元测试原则、实践和模式- Manning

其他回答

模拟:帮助模拟和检查结果交互。这些交互 SUT调用它的依赖项来改变它们的状态。

存根:帮助模拟传入的交互。这些相互作用称为 SUT对其依赖项进行处理以获取输入数据。

来源:单元测试原则、实践和模式- Manning

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

A fake is a generic term that can be used to describe either a stub or a mock object (handwritten or otherwise), because they both look like the real object. Whether a fake is a stub or a mock depends on how it’s used in the current test. If it’s used to check an interaction (asserted against), it’s a mock object. Otherwise, it’s a stub. Fakes makes sure test runs smoothly. It means that reader of your future test will understand what will be the behavior of the fake object, without needing to read its source code (without needing to depend on external resource). What does test run smoothly mean? Forexample in below code: public void Analyze(string filename) { if(filename.Length<8) { try { errorService.LogError("long file entered named:" + filename); } catch (Exception e) { mailService.SendEMail("admin@hotmail.com", "ErrorOnWebService", "someerror"); } } } You want to test mailService.SendEMail() method, to do that you need to simulate an Exception in you test method, so you just need to create a Fake Stub errorService class to simulate that result, then your test code will be able to test mailService.SendEMail() method. As you see you need to simulate a result which is from an another External Dependency ErrorService class.

我偶然看到了《小嘲笑者鲍勃叔叔》的一篇有趣的文章。它以一种非常容易理解的方式解释了所有的术语,因此对初学者很有用。Martin fowler的文章很难读,尤其是对于像我这样的初学者。

在codeschool.com的课程《Rails僵尸测试》中,他们给出了这些术语的定义:

Stub

用于将方法替换为返回指定结果的代码。

Mock

带有调用方法的断言的存根。

因此,正如Sean Copenhaver在他的回答中所描述的那样,不同之处在于mock设置了期望(即做出断言,关于是否或如何调用它们)。