首页 文章

如何在groovy spock测试中返回mock列表

提问于
浏览
2

从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 回答

  • 3

    您可以尝试将存根部分移动到交互检查阶段,例如

    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
    }
    

    你也不要't have to use JUnit' s assertEquals - Groovy允许你用 == 运算符比较两个对象 .

    我已经在简单的基于Spock的应用程序中检查了您的示例,它运行正常 . 我用Spock 0.7-groovy-2.01.0-groovy-2.41.2-groovy-2.4-SNAPSHOT 测试了它,适用于所有Spock版本 . 无论如何,我在过去有一些类似的问题和存根,因为交互检查在这些情况下做了伎俩 . 希望能帮助到你 .

  • 0

    根据白盒测试更好地测试完全相同的实现 . 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() 我们验证相同的引用 .

    因此,它不会影响列表的内容,它可能只是空的 .

相关问题