As an Android developer by day, I’m used to writing rigorous unit tests, taking
advantage of nice tools and libraries like JUnit and Mockito. However, as a
hobbyist game developer by night, I feel like my game project is a bit lacking
in terms of testing. How about we fix that?
First off, LibGDX doesn’t sport any unit tests for your game project whatsoever.
The project itself has lots of tests, which is nice, but they are Eclipse-only
at the time of writing this and don’t really lend themselves to properly testing
your own code. For instance, the base classes for the tests such as GdxTest
are not available for your production code. Bummer.
However, let’s not give up just yet. Getting your unit tests up and running takes
just a bit of extra effort. With your fresh game project created (or an
old one loaded up), let’s open the project-wide build.gradle and navigate to
the core project portion. You should see something like this:
Nothing special here - just the dependencies for LibGDX and some other stuff
you might have included. Now, we just need three new lines here. First, before
the dependencies, we declare the source directory for our unit tests:
This tells the project that your tests are located inside a folder called test,
just like when you’re working on an Android project. Next, let’s add two dependencies
for JUnit and Mockito:
Let’s create our first unit test now. Open a class you’d like to write your test
for, place your caret on the class name and hit Alt + Enter. This should Open
a contextual menu with the option “Create Test”.
Now, let’s write a simple test. I’ll write my test for my own class called
TilesetHandler which is a simple class for managing textures and tilesets.
My test would look something like this:
So far so good, but what happens when I try to run this?
Err… It appears that we don’t have the native dependencies of LibGDX when
we try to run our test. Well, let’s solve that! If you recall from our test
dependencies, there was a dependency for gdx-backend-headless which is normally
used for running your LibGDX application on a server. We can also use this headless
backend to run our tests!
First, let’s create a new test class called GameTest that will be the base
class for all our upcoming tests.
One more thing: make our actual test class extend from GameTest:
And there we go! Now your test should work as intended. Whoo!
LibGDX is a powerful library and framework to make games in, but unfortunately
unit testing your own code is made a tad difficult. Hopefully this post helps you
on your journey to greater test coverage and better quality of your code!