java - 为什么我们应该通过mock来了解邻居对象的信息?

标签 java unit-testing mocking jmock

可能是我误解了模拟对象的概念。我在stackoverflow看到一些帖子为了理解何时应该使用模拟对象。真的我不知道什么时候必须使用模拟对象。我举一个书Growing Object-Oriented Software, Guided by Tests的例子:

context.checking(new Expectations() {{
    oneOf (turtle).turn(45);
}});

使用很简单:

turn 方法只执行一次吗?如果为 true 测试将通过。如果没有,测试将失败。这就是我对mock对象的理解。

马丁·福勒在 Mocks Aren't Stubs说:

Mocks use behavior verification, where we instead check to see if the SUT made the correct calls on the collaborator.

但我的问题是,如果我们想要对 SUT 进行单元测试,为什么我们需要验证协作者对象(在本例中为 turtle)的行为?

最佳答案

正如所建议的,Martin Fowler 写了一篇非常有趣的文章 http://goo.gl/85qY您可以通过示例真正了解模拟和 stub 的概念。

首先要澄清您是否需要模拟或 stub 。

模拟是关于行为或方法的。

Mocks are what we are talking about here: objects pre-programmed with expectations which form a specification of the calls they are expected to receive.

当你进行单元测试时,你应该模拟类的协作者,因为他们没有被测试。例如,您用来持久保存数据源的对象,因为在单元测试期间您不想持久保存任何内容,请与系统的其余部分隔离进行测试。

stub

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. Stubs may also record information about calls, such as an email gateway stub that remembers the messages it 'sent', or maybe only how many messages it 'sent'.

例如看看 Mockito http://goo.gl/zujvY为了了解模拟框架可以做什么,但在澄清是否要测试对象的行为或状态之前。

关于java - 为什么我们应该通过mock来了解邻居对象的信息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25510828/

相关文章:

unit-testing - catch block 中的 PHPUnit 测试代码

c# - 除了使测试更容易之外,封闭系统中的接口(interface)还带来什么优势?

php - 模拟 WP_REST_Request 对象

java - 如何获取 Spring 3 的 spring-framework-3.0.5-RELEASE-with-dependencies.zip 文件?

python - Golang单元测试python函数

java - 方法本地字符串内存分配?

unit-testing - 模拟大返回结果

python - 忽略一次测试的类级别补丁装饰器

java - 从 SecureRandom 获取确定性值?

java - 如何获取 :errors tag by using MultiActionController? 形式的错误消息