-
Notifications
You must be signed in to change notification settings - Fork 2
Testing
The quickest way to learn is to look at the tests that are already written. Tests tend to look very similar, with quite a lot of duplicate code (yes, this time duplicate code is not so bad).
One important thing to keep in mind is that a unit test has to function entirely on it's own: any state that it builds up is destroyed when it finishes. Be careful with properties on the testclass, never count on them retaining their value from a previous test.
For a comprehensive guide, have a look here
Tip: add the following static import:
import static org.junit.jupiter.api.Assertions.*;
at the top of your test file, this will give you access to all the Junit assert
methods.
To test your sql queries, make a test class that extends the DatabaseTest
class. It provides you with a Jdbi
instance that you can easily use within your tests. The instance is re-initialized before every test, so you can assume the database is empty at the start of every test.
Here's a quick example of a DAO test class:
// imports are omitted
class BatonDAOTest extends DatabaseTest {
private BatonDAO batonDAO;
@Override
@BeforeEach
public void setUp() throws Exception {
// don't forget the super call when overriding the setUp method!!
super.setUp();
// make a batonDAO available for every test. Since this method is run before each test
// we can be sure that it is valid.
batonDAO = jdbi.onDemand(BatonDAO.class);
}
@Test
void createBaton() {
Baton testbaton = new Baton("testbaton");
final Id testId = batonDAO.insert(testbaton);
// there are no guarantees for the exact value of an auto-generated ID,
// so we don't test for them
assertTrue(testId.getId() > 0);
Optional<Baton> batonOptional = batonDAO.findBatonById(testId.getId());
assertFalse(batonOptional.isEmpty());
Baton baton = batonOptional.get();
// baton cannot be null here because of the previous assertion
assertEquals("testbaton", baton.getName());
}
}