Search code examples
javagradlejunit

Runing junit test via gradle doesn't show the expectation


Running: ./gradlew test triggers the test run successfully:

Task :test FAILED

PerfectNumberTest > Test calcPerfectNumbers() method FAILED
    org.opentest4j.AssertionFailedError at PerfectNumberTest.java:51

5 tests completed, 1 failed

However, I do not get the output which would indicate what exactly went wrong in the test,

For instance: expected 1 instead of 2

These are the dependencies which I'm using:

dependencies {
    testImplementation platform('org.junit:junit-bom:5.9.1')
    testImplementation 'org.junit.jupiter:junit-jupiter'
}

Solution

  • Use the following configuration to your build.gradle file:

    import org.gradle.api.tasks.testing.logging.TestExceptionFormat
    import org.gradle.api.tasks.testing.logging.TestLogEvent
    
    // ...
    
    tasks.withType(Test) {
        testLogging {
            // set options for log level LIFECYCLE
            events TestLogEvent.STARTED,
                       TestLogEvent.FAILED,
                       TestLogEvent.PASSED,
                       TestLogEvent.SKIPPED,
                       TestLogEvent.STANDARD_ERROR,
                       TestLogEvent.STANDARD_OUT
            exceptionFormat TestExceptionFormat.FULL
            showExceptions true
            showCauses true
            showStackTraces true
            info.events = debug.events
            info.exceptionFormat = debug.exceptionFormat
    
            afterSuite { desc, result ->
                if (!desc.parent) { // will match the outermost suite
                    def duration = String.format("%.3f sec", (result.endTime - result.startTime) / 1000)
                    def output = "Results: ${result.resultType} (${result.testCount} tests, ${result.successfulTestCount} passed, ${result.failedTestCount} failed, ${result.skippedTestCount} skipped) ${duration}"
                    def startItem = '|  ', endItem = '  |'
                    def repeatLength = startItem.length() + output.length() + endItem.length()
                    println('\n' + ('-' * repeatLength) + '\n' + startItem + output + endItem + '\n' + ('-' * repeatLength))
                }
            }
        }
    }
    

    This configuration will show everything even the console outuput

    See this post question for more details Gradle: How to Display Test Results in the Console in Real Time?