从Spock Groovy模拟接口返回所需对象列表时遇到问题:
public interface SomeRepository {
List<SomeObject> getAll();
}
所以我想在课堂上嘲笑:
@CompileStatic
class SomeProcessor {
private final SomeRepository repository
SomeProcessor(SomeRepository repository) {
this.repository = repository
}
List<SomeObject> getAll() {
return repository.all
}
}
我有那个测试:
class SomeProcessorSpec extends Specification {
private final SomeRepository repository = Mock(SomeRepository)
@Subject private final SomeProcessor processor = new SomeProcessor(repository)
def 'should collect items from repository'() {
given:
List<SomeObject> expected = [new SomeObject(), new SomeObject()]
repository.all >> expected
when:
List<SomeObject> actual = processor.all
then:
assertEquals(expected, actual)
}
}
当我尝试运行该测试时,我得到一个断言错误:
junit.framework.AssertionFailedError:预期:[com.example.SomeObject@1fa268de,com.example.SomeOjbect@4f6ee6e4]实际:null
所以这意味着它从 repository.all
方法返回 null
而不是我预期的列表,这让我感到困惑 . 问题是:在使用spock和groovy进行测试时,如何从模拟实例中实际返回列表?
2 回答
您可以尝试将存根部分移动到交互检查阶段,例如
你也不要't have to use JUnit' s
assertEquals
- Groovy允许你用==
运算符比较两个对象 .我已经在简单的基于Spock的应用程序中检查了您的示例,它运行正常 . 我用Spock
0.7-groovy-2.0
,1.0-groovy-2.4
和1.2-groovy-2.4-SNAPSHOT
测试了它,适用于所有Spock版本 . 无论如何,我在过去有一些类似的问题和存根,因为交互检查在这些情况下做了伎俩 . 希望能帮助到你 .根据白盒测试更好地测试完全相同的实现 .
processor.all
按原样返回repository.all
的结果 . 所以,更好地测试这个事实 .基于Szymon Stepniak提供的正确代码,测试可以简化为:
其中
.is()
我们验证相同的引用 .因此,它不会影响列表的内容,它可能只是空的 .