Reputation: 583
How would I go about testing the println
output of custom Gradle tasks? This is my code so far:
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!">>
}
}
Upvotes: 1
Views: 1563
Reputation: 2625
You can do this by using SystemOutputInterceptor This should look something like this:
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
}
}
EDIT: If you would like to use spock for Your's than You could also test this like that:
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)
}
}
mocking out System.out
in Java should be possible with PowerMock
Upvotes: 1
Reputation: 49231
The solution is to replace standard output stream with your implementation and then read data from it. You can do it for error end input streams too.
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!'
Upvotes: 0