import static org.junit.Assert.*

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

def events = []
// START SNIPPET 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 SNIPPET testListenerImpl

// START SNIPPET testListenerRegister
gradle.addListener(new MyListener(events: events))
// END SNIPPET 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)
}

