乐闻世界logo
搜索文章和话题

How to run only one unit test class using Gradle?

1个答案

1

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.

groovy
task 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:

groovy
dependencies { testImplementation 'junit:junit:4.12' }

Then, create a test class:

java
package 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.

2024年7月21日 19:50 回复

你的答案