[英]How to return list for mock in groovy spock test
我从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测试时,如何从模拟实例中实际返回列表?
您可以尝试将存根零件移至交互检查阶段,例如
def 'should collect items from repository'() {
given:
List<SomeObject> expected = [new SomeObject(), new SomeObject()]
when:
List<SomeObject> actual = processor.all
then:
1 * repository.all >> expected
and:
expected == actual
}
另外,您不必使用JUnit的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提供的正确代码,可以将测试简化为:
def 'should collect items from repository'() {
given:
def expected = []
when:
def actual = processor.all
then:
1 * repository.all >> expected
and: 'make sure we got the same expected list instance'
actual.is(expected)
}
在.is()
我们验证相同的引用。
结果,它不符合列表的内容,可以为空。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.