Gradle – How to run a single unit test class

In Gradle, we can pass an --tests option to run a single unit test class. Read this Gradle Test Filtering.

Terminal

gradle test --test TestClass

P.S Tested with Gradle 6.7.1

1. Run a single test class

Review a simple unit test.

DummyTest.java

package com.mkyong.security.db;

import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertTrue;

public class DummyTest {

    @Test
    void test_a_ok() {
        assertTrue(true);
    }

    @Test
    void test_b_ok() {
        assertTrue(true);
    }

}

To run only the above unit test, try gradle test --tests DummyTest.

Terminal

gradle test --tests DummyTest

2. Gradle –tests examples

I added the below configuration to display the Gradle test’s output in the console

build.gradle

test {
	testLogging {
		events "passed", "skipped", "failed", "standardOut", "standardError"
	}
}  

2.1 Run all tests from the test class DummyTest.

Terminal

gradle test --tests DummyTest

> Task :test

DummyTest > test_a_ok() PASSED

DummyTest > test_b_ok() PASSED

By default, Gradle skips the previously passed tests, and we can use cleanTest to force Gradle always to run the previously passed tests, even the tests are unmodified.

Terminal

gradle cleanTest test --tests DummyTest

2.2 Run a single test method.

Terminal

gradle test --tests DummyTest.test_b_ok

> Task :test

DummyTest > test_b_ok() PASSED

2.3 Gradle test supports wildcard *, enclose the wildcard with a single quote (bash shell?) or double quotes (zsh shell).

Terminal

# if single quote not working, try double quotes, depends on shell
gradle test --tests `Dummy*`

gradle test --tests "Dummy*"

> Task :test

DummyTest > test_a_ok() PASSED

DummyTest > test_b_ok() PASSED

2.4 Fully-qualified name pattern.

Terminal

gradle test --tests com.mkyong.security.db.DummyTest

2.5 Run all tests from a package.

Terminal

gradle test --tests "com.mkyong.security.*"

2.6 The --tests and the continuous build

Terminal

gradle test --continuous --tests DummyTest  

References

2 comments on “Gradle – How to run a single unit test class

  1. This will fail the build in a multi-module project, if in any of the other modules the test name (pattern) is not found. The article should explain how to avoid that.

    Reply
  2. Hello, in your first code segment it says

    gradle test –test TestClass

    despite it saying --tests everywhere else.
    Thanks!

    Reply

Leave a Comment

Your email address will not be published. Required fields are marked *