Search⌘ K
AI Features

Cleaning the Database and Mocking the Controller

Explore how to clean the database before and after tests to maintain test accuracy. Understand mocking controllers with Mockito to isolate dependencies and focus on testing application logic confidently.

We'll cover the following...

Database clean-up

Our tests for the controller empty the database both before and after each test method’s execution:

Java
//...
public class QuestionControllerTest {
private QuestionController controller;
@Before
public void create() {
controller = new QuestionController();
controller.deleteAll();
}
@After
public void cleanup() {
controller.deleteAll();
}
@Test
public void findsPersistedQuestionById() {
int id = controller.addBooleanQuestion("question text");
Question question = controller.find(id);
assertThat(question.getText(), equalTo("question text"));
}
@Test
public void questionAnswersDateAdded() {
Instant now = new Date().toInstant();
controller.setClock(Clock.fixed(now, ZoneId.of("America/Denver")));
int id = controller.addBooleanQuestion("text");
Question question = controller.find(id);
assertThat(question.getCreateTimestamp(), equalTo(now));
}
@Test
public void answersMultiplePersistedQuestions() {
controller.addBooleanQuestion("q1");
controller.addBooleanQuestion("q2");
controller.addPercentileQuestion("q3", new String[] { "a1", "a2"});
List<Question> questions = controller.getAll();
assertThat(questions.stream()
.map(Question::getText)
.collect(Collectors.toList()),
equalTo(Arrays.asList("q1", "q2", "q3")));
}
@Test
public void findsMatchingEntries() {
controller.addBooleanQuestion("alpha 1");
controller.addBooleanQuestion("alpha 2");
controller.addBooleanQuestion("beta 1");
List<Question> questions = controller.findWithMatchingText("alpha");
assertThat(questions.stream()
.map(Question::getText)
.collect(Collectors.toList()),
equalTo(Arrays.asList("alpha 1", "alpha 2")));
}
}

The code calls the QuestionController method deleteAll() in both the @Before and @After methods. When trying to figure out a problem, we might need to comment out the ...