How to reset between tests

robert trudel picture robert trudel · Dec 12, 2016 · Viewed 22.5k times · Source

I have a test class

@RunWith(SpringRunner.class)
@DataJpaTest

I have two tests. In every test I do the same operation, persist the object. Only the find call are different.

If I run both tests together they fail but if I run test one after another they are successful.

There is no reset between each test. How to do that? Only the call to the repository is different in each test.

@Test
public void findTopByCommerceCommerceIdOrderByEntryTimeDesc() {

    Long commerceId = 1L;

    Commerce commerce = new Commerce();
    commerce.setName("test");
    this.entityManager.persist(commerce);

    Member member = new Member();
    member.setCommerce(commerce);
    member.setMan(true);
    member.setName("bob binette");

    this.entityManager.persist(member);

    Visit visit1 = new Visit();
    visit1.setCommerce(commerce);

    visit1.setMember(member);
    visit1.setEntryTime(LocalDateTime.of(LocalDate.now(), LocalTime.now()));

    Visit visit2 = new Visit();
    visit2.setCommerce(commerce);

    visit2.setMember(member);
    visit2.setEntryTime(LocalDateTime.of(LocalDate.now().minusDays(2), LocalTime.now()));

    this.entityManager.persist(visit1);
    this.entityManager.persist(visit2);

    Visit visit = visitRepository.findTopByCommerceCommerceIdOrderByEntryTimeDesc(commerceId);

    assertEquals(visit.getVisitId(), Long.valueOf("1"));

}

Edit

i put all the code : http://pastebin.com/M9w9hEYQ

Answer

HPacquee picture HPacquee · Dec 19, 2016

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

@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)