2014-02-22 78 views
1

我將如何去測試自定義Gradle任務的輸出println?這是我的代碼到目前爲止: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!">> 
    } 
} 

回答

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) 
    } 
} 

在Java中嘲笑System.out應該是po可以用PowerMock

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!' 
相關問題