您可以通過使用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