How to reset between tests How to reset between tests spring spring

How to reset between tests


Add the @DirtiesContext annotation, but provide it with the AFTER_EACH_TEST_METHOD classMode

@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)


In your case for each test you persist the same data. So you should persist data before all test or persist before each test and clean after it.

1. Persist before all test

@BeforeClasspublic static void init(){  //persist your data}@AfterClasspublic static void clear(){  //remove your data}@Testpublic void findTopByCommerceCommerceIdOrderByEntryTimeDesc() {    Visit visit = visitRepository.findTopByCommerceCommerceIdOrderByEntryTimeDesc(commerceId);    assertEquals(visit.getVisitId(), Long.valueOf("1"));}

In this case @AfterClass is optionally

2. Persist before each test and clean after each test

    @Before    public void init(){      //persist your data    }    @After    public void clear(){      //remove your data    }    @Test    public void findTopByCommerceCommerceIdOrderByEntryTimeDesc() {        Visit visit = visitRepository.findTopByCommerceCommerceIdOrderByEntryTimeDesc(commerceId);        assertEquals(visit.getVisitId(), Long.valueOf("1"));    }

Remember that methods which use @BeforeClass and @AfterClass must be static.


You can use @DirtiesContext annotation on your test class to reset the tests, there you can also choose when to reset. Default is after every method, but you can change that by passing in different parameters to the @DirtiesContext annotation.

import org.springframework.test.annotation.DirtiesContext;@RunWith(SpringRunner.class)@DataJpaTest@DirtiesContextpublic class VisitRepositoryTest {