Gradle Command to Run Test Cases

In this guide, we'll dive into how to execute tests using Gradle. 

Prerequisites

  • A Java project set up with Gradle. 
  • Gradle installed on your machine or the Gradle Wrapper included in your project. 
  • Some test cases are written (e.g., using JUnit or TestNG) within your project. 

Running All Tests 

1. Navigate to your project directory 

Open your terminal or command prompt and go to the root directory of your Gradle project. 

2. Execute the test task 

Run the following command:

gradle test

If you're using the Gradle Wrapper (often recommended for consistent builds):

./gradlew test

For Windows:

gradlew.bat test

Inspecting the Results 

By default, Gradle will generate a report once all tests are executed. You can find this report in HTML format at build/reports/tests/test/index.html. Open it in any web browser to view a detailed overview of all executed tests, including those that passed and failed. 

Running Specific Tests 

If you only want to run a subset of your tests, you can do so using the --tests flag:

gradle test --tests com.example.MyTestClass

Replace com.example.MyTestClass with the full name of the test class you want to run. To run specific methods within a test class:

gradle test --tests com.example.MyTestClass.myTestMethod

Wildcards can also be used:

gradle test --tests com.example.*  // will run all tests in the com.example package

Continuous Test Execution 

Gradle allows for continuous testing which means it will keep running in the background, watching for changes in your files, and re-run tests when it detects changes. This can be activated using the -t flag:

gradle test -t

Conclusion 

Running tests with Gradle is a breeze. The tool offers flexibility, allowing developers to run all tests, specific tests, or even enable continuous testing. This makes the feedback loop shorter, and errors can be caught early during development. With the test reports generated, one can also get an overview of the project's test health. Always remember that consistent testing leads to more reliable software.

Comments