Search⌘ K
AI Features

Testing Databases

Explore how to write tests for Java methods that interact with database controllers using JUnit. Understand challenges with dependencies on Postgres databases via JPA, learn when to use unit tests versus integration tests, and gain techniques to verify correct wiring between code and database components for reliable functionality.

We were able to refactor this class so that most of its code doesn’t directly interact with a QuestionController instance, which in turn lets us write fast tests for the bulk of its logic. We were left with one method, questionText(), that interacts with a controller object. Let’s test that method:

Java
public Map<Integer,String> questionText(List<BooleanAnswer> answers) {
Map<Integer,String> questions = new HashMap<>();
answers.stream().forEach(answer -> {
if (!questions.containsKey(answer.getQuestionId()))
questions.put(answer.getQuestionId(),
controller.find(answer.getQuestionId()).getText()); });
return questions;
}

The questionText() method takes a list of answer objects and returns a ...