Let's suppose you want to create unit tests for a game.
You have the Player
class, which has a local variable of the World
class (instantiated by the construtor) and the World
object has an open connection to the database.
So player.breakBlock()
method would call world.breakBlockAt(x,y,z)
and world.breakBlockAt(int x, int y, int z)
method would perform changes to the database and return the result.
In cases like this where you have complex "object dependencies", what would be the best way to perform testing?
Currently I'm basically starting the whole game environment, with a test database, spawning a fake Player and using it for the testing.
To test your Player
class without a database, you could use a mocking framework like EasyMock or Mockito to create a mock of your World
object, pre-record the methods you expect your Player
class to call and then verify later that the method was actually called.
You can also let your mock objects intercept the method call and replace it with custom logic. You could for example delegate the call breakBlockAt
to a method that modifies a HashMap
instead of an actual database. And the returned value could then behave differently depending on what previous calls already did to the HashMap
.
Of course you should still have a separate test case for your World
class as well, to actually test the logic that works with the database (but without adding the complexity of the Player
class on top). This is basically an integration test where you make sure that the JDBC statements or JPA objects result in valid SQL that works when used with the database dialect of your choice.
A library like Testcontainers can be used to set up an empty database in a Docker container from within your unit test. The only requirement is that your test environment has Docker running and ready for execution.