Dean Hiller
Dean Hiller

Reputation: 20200

how to get test timing information from gradle output during build?

I would like to get timing information on how long it took a whole *.java class to run AND timing information on each test as well in the gradle output. Is there a way to do that with gradle?

Currently, I just have

  beforeTest{ descr ->
    logger.warn("Starting Test ${descr.className} : ${descr.name}")
  }

Upvotes: 4

Views: 3891

Answers (3)

Max Farsikov
Max Farsikov

Reputation: 2763

Gragle 8.5, Kotlin, to print 3 longest tests:

data class TestDuration(val name: String, val duration: Duration) {
    override fun toString() = "$name $duration"
}

val testDurations = mutableListOf<TestDuration>()

tasks.test {
    useJUnitPlatform()

    addTestListener(object : TestListener {
        override fun beforeSuite(suite: TestDescriptor) {}
        override fun afterSuite(suite: TestDescriptor, result: TestResult) {}
        override fun beforeTest(testDescriptor: TestDescriptor) {}
        override fun afterTest(testDescriptor: TestDescriptor, result: TestResult) {
            testDurations.add(
                TestDuration(
                    name = "${testDescriptor.className}.${testDescriptor.name}",
                    duration = Duration.ofMillis(result.endTime - result.startTime)
                )
            )
        }
    })

    doLast {
        println("Longest 3 tests")
        testDurations.sortedBy { it.duration }
            .reversed()
            .take(3)
            .forEach { println(it) }
    }
}

Upvotes: 2

Vadzim
Vadzim

Reputation: 26180

A variation of the accepted answer with rounding millis to seconds:

test {
    afterSuite { descriptor, result ->
        def duration = java.util.concurrent.TimeUnit.MILLISECONDS
                .toSeconds(result.endTime - result.startTime)
        println "Total duration of $descriptor: $duration seconds"
    }
}

Upvotes: 0

Ivan Frolov
Ivan Frolov

Reputation: 1048

It depends on your intent. For debugging purposes, I usually run gradle with --profile flag, which generates the full report of task execution times. See Gradle Command Line.

If you wish to do something ad-hoc with times, you'd need to code the desired behavior. For example, this will print execution time for each test:

test {
  afterTest { descriptor, result ->
    def totalTime = result.endTime - result.startTime
    println "Total time of $descriptor.name was $totalTime"
  }
}

See also:

Upvotes: 8

Related Questions