buildscript {
  repositories.mavenCentral()
  dependencies.classpath 'junit:junit:4.+'
}
import static org.junit.Assert.*

apply plugin: 'java'
repositories.mavenCentral()
dependencies.testCompile 'junit:junit:4.+'
test.ignoreFailures = false

def events = []
// tag::testListenerImpl[]
class MyListener implements org.gradle.api.tasks.testing.TestListener
{
    def events

    public void beforeSuite(TestDescriptor suite) {
        recordAndOutput('suiteStarting: '+suite.getName())
    }

    public void afterSuite(TestDescriptor suite, TestResult result) {
        recordAndOutput 'suiteFinished: '+suite.getName()
    }

    public void beforeTest(TestDescriptor test) {
        recordAndOutput 'testStarting: '+test.getName()
    }

    public void afterTest(TestDescriptor test, TestResult result) {
        recordAndOutput 'testFinished: '+test.getName()+', result: '+result.getResultType()
    }

    private void recordAndOutput(String msg) {
        events << msg
        println '  '+msg
    }
}
// end::testListenerImpl[]

// tag::testListenerRegister[]
gradle.addListener(new MyListener(events: events))
// end::testListenerRegister[]

test.doLast {
    def expectedEvents = []
    expectedEvents << 'suiteStarting: DoNothingTest'
    expectedEvents << 'testStarting: doNothing(DoNothingTest)'
    expectedEvents << 'testFinished: doNothing(DoNothingTest), result: SUCCESS'
    expectedEvents << 'testStarting: doNothingButFail(DoNothingTest)'
    expectedEvents << 'testFinished: doNothingButFail(DoNothingTest), result: FAILURE'
    expectedEvents << 'testStarting: doNothingButError(DoNothingTest)'
    expectedEvents << 'testFinished: doNothingButError(DoNothingTest), result: FAILURE'
    expectedEvents << 'suiteFinished: DoNothingTest'

    assertEquals(expectedEvents, events)
}

