Database cleanup after Junit tests Database cleanup after Junit tests database database

Database cleanup after Junit tests


If you are using Spring, everything you need is the @DirtiesContext annotation on your test class.

@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration("/test-context.xml")@DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD)public class MyServiceTest {   ....}


Unless you as testing specific database actions (verifying you can query or update the database for example) your JUnits shouldn't be writing to a real database. Instead you should mock the database classes. This way you don't actually have to connect and modify the database and therefor no cleanup is needed.

You can mock your classes a couple of different ways. You can use a library such as JMock which will do all the execution and validation work for you. My personal favorite way to do this is with Dependency Injection. This way I can create mock classes that implement my repository interfaces (you are using interfaces for your data access layer right? ;-)) and I implement only the needed methods with known actions/return values.

//Example repository interface.public interface StudentRepository{   public List<Student> getAllStudents();}//Example mock database class.public class MockStudentRepository implements StudentRepository{   //This method creates fake but known data.   public List<Student> getAllStudents()   {      List<Student> studentList =  new ArrayList<Student>();      studentList.add(new Student(...));      studentList.add(new Student(...));      studentList.add(new Student(...));      return studentList;   }}//Example method to test.public int computeAverageAge(StudentRepository aRepository){   List<Student> students = aRepository.GetAllStudents();   int totalAge = 0;   for(Student student : students)   {      totalAge += student.getAge();   }   return totalAge/students.size();}//Example test method.public void testComputeAverageAge(){   int expectedAverage = 25; //What the expected answer of your result set is   int actualAverage = computeAverageAge(new MockStudentRepository());   AssertEquals(expectedAverage, actualAverage);}