首页 > 解决方案 > @DirtiesContext 不清除数据库

问题描述

我已经尝试了以下步骤,但遗憾的是没有运气:

方法号 1 总是失败,因为大小预期为 1,但它的 2 -> 测试单独运行成功通过,但是当我运行所有应用程序测试时,正是那个失败

1)用标记每个方法 @DirtiesContext(methodMode = DirtiesContext.MethodMode.BEFORE_METHOD)

2)在课堂上标记@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_EACH_TEST_METHOD)

3)标记方法@Transactional

  @SpringBootTest
public class ExportServiceTest {

    @Autowired
    ExportService exportService;

    @Autowired
    ExportRepository exportRepository;

    @Autowired
    UserRepository userRepository;


    @Test
    public void onlyOneExportUserShouldBeAddedWithMultipleEntries() {
        UserEntity userEntity = new UserEntity().setId(2L);
        exportService.createIfNotExist(userEntity);
        exportService.createIfNotExist(userEntity);
        Assertions.assertThat(exportRepository.findAll()).hasSize(1);
    }

    @Test
    public void exportUserShouldBeAdded() {
        UserEntity userEntity = new UserEntity().setId(1L);
        exportService.createIfNotExist(userEntity);
        Optional<UserExportEntity> exportUser = exportRepository.findByUserEntityId(userEntity.getId());
        Assertions.assertThat(exportUser).isPresent();
    }

    @Test
    public void shouldHaveTwoRecordsInExport() {
        UserEntity userEntity = new UserEntity().setId(1L).setEmail("test@test.com");
        UserEntity userEntity2 = new UserEntity().setId(2L).setEmail("test1@test.com");
        userRepository.save(userEntity);
        userRepository.save(userEntity2);
        exportService.createIfNotExist(userEntity2);
        exportService.createIfNotExist(userEntity);
        Assertions.assertThat(exportRepository.findAll()).hasSize(2);
    }
}

标签: javaspring

解决方案


推荐阅读