Spock mocking inputStream causes infinite loop

非 Y 不嫁゛ 提交于 2019-12-24 08:25:22

问题


I have a code:

gridFSFile.inputStream?.bytes

When I try to test it this way:

given:
def inputStream = Mock(InputStream)
def gridFSDBFile = Mock(GridFSDBFile)
List<Byte> byteList = "test data".bytes
...
then:
1 * gridFSDBFile.getInputStream() >> inputStream
1 * inputStream.getBytes() >> byteList
0 * _

The problem is that inputStream.read(_) is called infinite number of times. When I remove the 0 * _ - the test hangs until garbage collector dies.

Please advise how can I properly mock the InputStream without falling into infinite loops i.e. to be able to test the row above with 2 (or like that) interactions.


回答1:


The following test works:

import spock.lang.Specification

class Spec extends Specification {

    def 'it works'() {
        given:
        def is = GroovyMock(InputStream)
        def file = Mock(GridFile)
        byte[] bytes = 'test data'.bytes

        when:
        new FileHolder(file: file).read()

        then:
        1 * file.getInputStream() >> is
        1 * is.getBytes() >> bytes
    }

    class FileHolder {
        GridFile file;

        def read() {
            file.getInputStream().getBytes()
        }
    }

    class GridFile {
        InputStream getInputStream() {
            null
        }
    }
}

Not 100% sure about it but it seems that you need to use GroovyMock here since getBytes is a method added dynamically by groovy. Have a look here.



来源:https://stackoverflow.com/questions/43014523/spock-mocking-inputstream-causes-infinite-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!