Unit Testing

From GT New Horizons

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

    // Extra unit testing libraries

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 {
    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.

Writing unit tests

Dealing with ItemStacks

Need to test simple handling of ItemStacks? You can't use the game's regular item registry without loading into class loading issues, but you can get a lot done by creating your own Item and ItemStack instances in your test context:

ItemStack ITEMSTACK = new ItemStack(new Item());