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