Gradle:如何测试自定义任务输出(println)

时间:2014-02-22 17:59:52

标签: java gradle

我如何测试自定义Gradle任务的println输出?到目前为止,这是我的代码:

class TaskTest {
    @Test
    void testSomething() {
        Project project = ProjectBuilder.builder().build()
        def task = project.task('testTask', type: Task)
        task.execute()
        <<assert task did println "Hello, world!">>
    }
}

2 个答案:

答案 0 :(得分:1)

您可以使用SystemOutputInterceptor执行此操作。这应该是这样的:

import groovy.ui.SystemOutputInterceptor

class TaskTest {
    @Test
    void testSomething() {
        def expected = 'expectedOutput'
        def actual ='';
        def interceptor = new SystemOutputInterceptor({ actual += it; false});

        Project project = ProjectBuilder.builder().build()
        def task = project.task('testTask', type: Task)

        interceptor.start()
        task.execute()
        interceptor.stop()

        assert actual.trim() == expected
    }
}

修改 如果您想使用spock作为您的,那么您也可以这样测试:

class TaskTest extends spock.lang.Specification {
  def "should print test to stdout"() {
    given:
    def expected = 'expectedOutput'
    System.out = Mock(PrintStream)
    Project project = ProjectBuilder.builder().build()
    def task = project.task('testTask', type: Task)

    when:
    task.execute()

    then:
    1 * System.out.println(expected)
  }
}

使用PowerMock

可以在Java中模拟System.out

答案 1 :(得分:0)

解决方案是用您的实现替换标准输出流,然后从中读取数据。您也可以为错误结束输入流执行此操作。

def stdout = System.out
def os = new ByteArrayOutputStream()

System.out = new PrintStream(os)
println 'Hello World!' // implicit flush

def array = os.toByteArray()
def is = new ByteArrayInputStream(array)
System.out = stdout

def line = is.readLines()[0]
assert line == 'Hello World!'