有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Spock模拟inputStream导致无限循环

我有一个密码:

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个(或类似)交互来测试上面的行


共 (1) 个答案

  1. # 1 楼答案

    以下测试工作:

    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