问题
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.
回答1:
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.
来源:https://stackoverflow.com/questions/43014523/spock-mocking-inputstream-causes-infinite-loop