When using the Gradle build system, you can run specific unit test classes by configuring tasks or specifying parameters directly via the command line. Here are several common methods:
1. Using Command Line Parameters
You can directly specify the test class to run using the --tests parameter in the command line. For example, to run the test class named MyClassTest, use the following command:
bash./gradlew test --tests com.example.MyClassTest
Here, com.example.MyClassTest is the fully qualified class name of the unit test class. To run a specific method within the test class, further specify the method name:
bash./gradlew test --tests "com.example.MyClassTest.myTestMethod"
2. Configuring Gradle Scripts
If you frequently need to run a specific test class, configure a dedicated task in the build.gradle file to run it. This avoids having to specify the full class name repeatedly in the command line.
groovytask myClassTest(type: Test) { include '**/MyClassTest.*' }
Run this task with the following command:
bash./gradlew myClassTest
Example: Creating and Running Unit Tests
Here is a basic example demonstrating how to create and run unit tests in a Java project using JUnit.
First, ensure your build.gradle file includes the JUnit dependency:
groovydependencies { testImplementation 'junit:junit:4.12' }
Then, create a test class:
javapackage com.example; import org.junit.Test; import static org.junit.Assert.assertEquals; public class MyClassTest { @Test public void testAdd() { MyClass myClass = new MyClass(); assertEquals(10, myClass.add(7, 3)); } }
Now, you can use any of the methods described earlier to run MyClassTest.
These methods are applicable to most Java projects using Gradle, helping developers run unit tests flexibly in both development and continuous integration environments.