Unit Testing

From GT New Horizons
Revision as of 03:26, 15 January 2024 by YannickMG (talk | contribs) (Started a page describing unit testing in GTNH repositories.)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)


Unit testing helps you write error free code.

Adding unit tests to a repository

If you want to add unit tests to a repository that lacks them, follow these steps. This assumes you want to use JUnit which is a popular unit testing framework you can learn about here.

1. Add dependencies

Add the following lines to dependencies.gradle.

    // Core unit testing platform
    testImplementation(platform('org.junit:junit-bom:5.9.2'))
    testImplementation('org.junit.jupiter:junit-jupiter')

    // Extra unit testing libraries
    testImplementation('org.assertj:assertj-core:3.+')
    testImplementation('org.mockito:mockito-core:5.+')

2. Configure the Gradle test task

Add the following task to the addon.gradle file. Create it at the root of the repository if it isn't present.

test {
    useJUnitPlatform()
    testLogging {
        events "passed", "skipped", "failed"
    }
}

3. Add the test source folder

Create the src/test/java and ensure your IDE recognizes it as a test source code folder.

To do this in IntelliJ simply right click the src folder and add the test\java directory from the preset list of directories.

You can now start adding and running unit tests.

Running unit tests

Don't use the Build and Test run configuration while writing your code.

To make sure your setup is correct, you can create a test that should fail and make sure the build task fails.

This being said, do not use the regular build task to run your unit tests while writing your code. Unit tests should run quickly to be useful and you do not need to do all the work that a regular build does, including code format checking.

In most IDEs you should be able to right click on the test source folder or your test class to run them directly.