我有一个代码:
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/