Run JUnit tests using Gradle test task
Preconditions (2)
✅ Expected Result: Gradle runs all JUnit tests and reports test summary showing all tests passed
/* * This is a sample JUnit 5 test class to be run by Gradle test task. * Save this file under src/test/java/com/example/ExampleTest.java */ package com.example; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; public class ExampleTest { @Test void addition_shouldReturnCorrectSum() { int result = 2 + 3; assertEquals(5, result, "2 + 3 should equal 5"); } } /* * To run tests, open terminal at project root and run: * gradle test * * Gradle will compile and run all tests under src/test/java. * Test results will be shown in console and saved under build/reports/tests/test/index.html */
This code defines a simple JUnit 5 test class with one test method.
The test method checks that 2 + 3 equals 5 using assertEquals. This is a basic assertion to verify test execution.
Gradle automatically detects and runs all tests in src/test/java when you run gradle test.
The test results appear in the console and also generate an HTML report under build/reports/tests/test/index.html.
This setup follows Gradle conventions and JUnit 5 best practices for test automation.
Now add data-driven testing with 3 different input values for addition
test task in a JUnit project?test task roletest task in Gradle is designed to run automated tests, such as those written with JUnit, to verify code correctness.compileJava compile code, clean removes build files, and deployment is separate. Only test runs tests.test = run tests [OK]gradle test. This triggers the test task which runs JUnit tests.runTests, executeTests, and checkTests are not standard Gradle commands and will cause errors.gradle test [OK]build.gradle:
test {
useJUnitPlatform()
testLogging {
events "passed", "failed"
}
}
What will be the output when you run gradle test and all tests pass?testLogging configurationtestLogging block with events "passed", "failed" means Gradle will log passed and failed test events when they occur.build.gradle:
test {
useJUnitPlatform()
testLogging {
events "passed", "failed"
}
include '**/MyTests.java'
}
But running gradle test runs no tests. What is the likely problem?include pattern filters test classes by their compiled class file names, not source files. It should match **/MyTests.class or use package style with forward slashes.**/MyTests.java does not match any compiled test classes, so no tests run.test task to run only tests tagged with @Tag("fast") in JUnit 5. Which build.gradle snippet correctly configures this?useJUnitPlatform accepts a configuration block where you can specify includeTags to run only tests with certain tags.includeTags 'fast' inside the useJUnitPlatform block. Other options place it incorrectly or omit useJUnitPlatform.Pass the test and this pattern moves unknown