java - Spock模拟inputStream导致无限循环

标签 java unit-testing grails groovy spock

我有一个代码:

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动态添加的方法。看看here .

关于java - Spock模拟inputStream导致无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43014523/

相关文章:

hibernate - 将整个表加载到缓存Grails中

java - 在 github 存储库中托管私有(private) Maven Artifact

scala - 在scalatest中测试方法时,是否可以模拟/ stub 在方法调用中实例化的对象?

node.js - 在 Jest 中模拟 Redis - NestJS

postgresql - 从gsp中的数据库(postgresql)检索一百万个数据

grails - Grails JMS队列注释失败,带有最终参数

java - 从 Java Applet 上的控件捕获文本

java - 无法在 Spark session 中配置 GeoSpark :

java - 使用 Appium for java 的 ios UI 自动化。无法使用 xPath 找到元素

api - 测试调用相同私有(private)方法的多个公共(public)方法