Spock嘲笑inputStream导致无限循环 [英] Spock mocking inputStream causes infinite loop
问题描述
我有一个代码:
gridFSFile.inputStream?.bytes
当我尝试以这种方式测试时:
给出:
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(或类似的)交互来测试上面的行。
$ p $
import spock.lang.Specification
class规格{b
$ b def'it works'(){
给定:
def is = GroovyMock(InputStream)
def file = Mock(GridFile)
byte [] bytes ='test data'.bytes
when:
new FileHolder(file:file).read()
then:
1 * file.getInputStream()>>是
1 * is.getBytes()>>字节
}
类FileHolder {
GridFile文件;
read read(){
file.getInputStream()。getBytes()
}
}
class GridFile {
InputStream getInputStream(){
null
}
}
}
不是100%确定的,但由于 getBytes
是因为您似乎需要在这里使用 GroovyMock
一种由groovy动态添加的方法。看看 here 。
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.
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.
这篇关于Spock嘲笑inputStream导致无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!