在尝试使用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
后,结果如下:
@After
上的deleteAll()
:
@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_
@AfterTransaction
中的 deleteAll()
方法会在输出的 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=?
hibernate.show_sql=true
设置为true。这将确保我们知道删除SQL是否被触发。 - The Coderhibernate.show_sql=true
发送结果即可。 - Pablo Souza