Spring CrudRepository deleteAll()什么都不做

问题描述 投票:0回答:1

当我尝试通过Spring的CrudRepository从我的数据库中删除所有记录时测试Controller类,但似乎没有发生任何事情。默认情况下似乎没有刷新。

我从未尝试使用Junit测试在浏览器中的真实控制器调用中使用此存储库,但我认为它可以正常工作! :)

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
@ActiveProfiles("test")
@Transactional
public class CostumerControllerIntegrationTest {

    @Autowired
    private MockMvc mockMvc;

    @Autowired
    private CostumerService costumerService;

    private Costumer costumer;

    @Before
    public void before() {
        this.costumer = this.exampleBuilder();
        costumerService.saveAll(this.costumer);
    }

    @After
    public void after() {
        costumerService.deleteAll();
    }

    @Test
    public void Should_ReturnStandardError_When_NotFoundById() throws Exception {
        //implementation
    }


private Costumer exampleBuilder() {

    Costumer costumer = new Costumer("Test", "Test", "Test", CostumerType.LEGAL_PERSON);
    State state = new State("Example State");
    City city = new City("Example Sity", state);
    Address address = new Address("Example Address",
            "Example Address", "Example Address",
            "Example Address", city, costumer);

    costumer.getAddresses().add(address);

    return costumer;
}

}

@Service
@Transactional
public class CostumerService {

    @Autowired
    private CostumerRepository repository;

    public void deleteAll() {
        repository.deleteAll();
    }

   //another methods

}

存储库扩展了CrudRepository

@Repository
public interface CostumerRepository extends CrudRepository<Costumer, Integer> {

}

在根据@TheCoder注释启用显示sql hibernate.show_sql=true后,结果为:

deleteAll()上的@After

@After
public void after() {
    costumerService.deleteAll();
}

输出sql:

2019-02-27 06:07:06 - HHH000397: Using ASTQueryTranslatorFactory
Hibernate: 
    select
        costumer0_.id as id1_3_,
        costumer0_.cpf_cnpj as cpf_cnpj2_3_,
        costumer0_.email as email3_3_,
        costumer0_.name as name4_3_,
        costumer0_.type as type5_3_ 
    from
        costumers costumer0_

deteleAll()上的@AfterTransaction输出sql包含删除查询。

@AfterTransaction
    public void afterTransatcion(){
        // List<Costumer> costumers = costumerService.findAll();
        costumerService.deleteAll();
    }


Hibernate: 
    select
        costumer0_.id as id1_3_,
        costumer0_.cpf_cnpj as cpf_cnpj2_3_,
        costumer0_.email as email3_3_,
        costumer0_.name as name4_3_,
        costumer0_.type as type5_3_ 
    from
        costumers costumer0_
Hibernate: 
    delete 
    from
        phones 
    where
        costumer_id=?
Hibernate: 
    delete 
    from
        costumers 
    where
        id=?
java spring-boot spring-data-jpa integration-testing
1个回答
-1
投票

交易结束时,数据将从数据库中删除。哪个应该只在测试方法的最后发生。

但是,因为您正在使用事务测试,所有事务将在测试后自动回滚。

默认情况下,测试完成后将自动回滚测试事务;但是,事务提交和回滚行为可以通过@Commit和@Rollback注释以声明方式配置

© www.soinside.com 2019 - 2024. All rights reserved.