斯波克嘲笑输入流导致无限循环



我有一个代码:

gridFSFile.inputStream?.bytes

当我尝试以这种方式测试它时:

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 * _

问题是inputStream.read(_)被调用了无限次。当我删除0 * _时 - 测试挂起,直到垃圾收集器死亡。

请告知我如何才能正确地模拟InputStream而不会陷入无限循环,即能够通过 2 次(或类似(交互来测试上面的行。

以下测试有效:

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
        }
    }
}

不是 100% 确定,但似乎您需要在此处使用GroovyMock getBytes因为它是 groovy 动态添加的方法。看看这里。

最新更新