ChatGPT解决这个技术问题 Extra ChatGPT

How to run JUnit tests with Gradle?

Currently I have the following build.gradle file:

apply plugin: 'java'

sourceSets {
    main {
        java {
            srcDir 'src/model'
        }
    }
}

dependencies {
    compile files('libs/mnist-tools.jar', 'libs/gson-2.2.4.jar')
    runtime fileTree(dir: 'libs', include: '*.jar')
}    


This build.gradle file is for my repository here. All of my main files are in src/model/ and their respective tests are in test/model.

How do I add a JUnit 4 dependency correctly and then run those tests in the folders of tests/model?


V
Vic Seedoubleyew

How do I add a junit 4 dependency correctly?

Assuming you're resolving against a standard Maven (or equivalent) repo:

dependencies {
    ...
    testCompile "junit:junit:4.11"  // Or whatever version
}

Run those tests in the folders of tests/model?

You define your test source set the same way:

sourceSets {
    ...

    test {
        java {
            srcDirs = ["test/model"]  // Note @Peter's comment below
        }
    }
}

Then invoke the tests as:

./gradlew test

EDIT: If you are using JUnit 5 instead, there are more steps to complete, you should follow this tutorial.


srcDirs = ["test/model"] is a bit more precise because it gets rid of the default test sources directory, whereas srcDir "test/model" adds another directory. Same for the main source set.
D
DivDiff

If you set up your project with the default gradle package structure, i.e.:

src/main/java
src/main/resources
src/test/java
src/test/resources

then you won't need to modify sourceSets to run your tests. Gradle will figure out that your test classes and resources are in src/test. You can then run as Oliver says above. One thing to note: Be careful when setting property files and running your test classes with both gradle and you IDE. I use Eclipse, and when running JUnit from it, Eclipse chooses one classpath (the bin directory) whereas gradle chooses another (the build directory). This can lead to confusion if you edit a resource file, and don't see your change reflected at test runtime.


To direct Eclipse build files to the same dir as Gradle (can prevent a few frustrating errors): Project --> Properties --> Java build path --> Default output folder: replace "bin" with "build". However... in my experience this seems to have the disconcerting habit of "slipping back" to the default "bin" every so often unexpectedly. Would be nice to know if there's a way of getting Eclipse to use "build" by default.
@mike-rodent as far as i know it is explicitly discouraged to share the same build path for eclipse and gradle (see e.g. discuss.gradle.org/t/…)
OK, I stand corrected! ... and I suppose there's nothing to be gained from compiling to the same dir. For most purposes the eclipse builder functionality becomes a mere validation tool: "whoops, this won't compile because of x, y and z".
@DivDiff my src folders structure is setup in the same way mentioned above, but still when i do gradle test, it doesn't do anything. It doesn't run my tests at all. Any idea?
@Gaurav, I invited you to a chatroom so we can talk about it offline.
d
daka

If you created your project with Spring Initializr, everything should be configured correctly and all you need to do is run...

./gradlew clean test --info

Use --info if you want to see test output.

Use clean if you want to re-run tests that have already passed since the last change.

Dependencies required in build.gradle for testing in Spring Boot...

dependencies {
    compile('org.springframework.boot:spring-boot-starter')
    testCompile('org.springframework.boot:spring-boot-starter-test')
}

For some reason the test runner doesn't tell you this, but it produces an HTML report in build/reports/tests/test/index.html.


M
Mahozad

This is for Kotlin DSL (build.gradle.kts) and using JUnit 5 (JUnit platform):

tasks.test {
    // Discover and execute JUnit4-based tests
    useJUnit()

    // Discover and execute TestNG-based tests
    useTestNG()

    // Discover and execute JUnit Platform-based (JUnit 5, JUnit Jupiter) tests
    // Note that JUnit 5 has the ability to execute JUnit 4 tests as well
    useJUnitPlatform()
}

dependencies {
    testImplementation("org.junit.jupiter:junit-jupiter:5.8.2")
    // ...
}

r
rob2universe

testCompile is deprecated. Gradle 7 compatible:

dependencies {
...
   testImplementation 'junit:junit:4.13'
}

and if you use the default folder structure (src/test/java/...) the test section is simply:

test {
    useJUnit()
}

Finally:

gradlew clean test

Alos see: https://docs.gradle.org/current/userguide/java_testing.html


B
Braian Coronel

If you want to add a sourceSet for testing in addition to all the existing ones, within a module regardless of the active flavor:

sourceSets {
    test {
        java.srcDirs += [
                'src/customDir/test/kotlin'
        ]
        print(java.srcDirs)   // Clean
    }
}

Pay attention to the operator += and if you want to run integration tests change test to androidTest.

GL