上下文
我正在测试带有 @Transactional 注释的方法。
商务舱内的测试方法
@Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRES_NEW, rollbackFor = UniquekeyException.class)
public void saveContact(ContactDto dto) throws BadRequestException, UniquekeyException {
Customer customer =this.authenticationFacade.getCustomerLoggedIn();
customer.setFromDto(dto);
this.customerRepository.save(customer);
}
单元测试
@Autowired
private CustomerRepository customerRepository;
@Autowired
private BisinessCustomer bisinessCustomer;
@Autowired
private CustomerRepository customerRepository;
@Test
@WithMockUser(username=USERNAME, password = PASSWORD)
public void saveContactDtoTest(){
//setup
ContactDto contact = this.getContactDto();
//exec
this.bisinessCustomer.saveContactDto(contact);
//assert
Assert.assertEquals(this.customerRepository.findByUsername(USERNAME).getContact.getAdress(), contact.getAdress());
//First value return null!!! When remove transactional anotation return the same that contact.getAdress()
}
问题
当我从 @Test 方法调用它时,它不会保留任何内容。
当我从目标方法中删除 @Transactional 注释时,一切正常,并且在测试中保持正常。
当我运行测试并且使用迁移flyway、mysql、spring、hirbernate、springboot时,数据库位于内存中。
问题
我可以配置 @Transactional 注解以在运行测试时排除它吗?
谢谢。
最佳答案
您可以轻松使用@Rollback(false)注释。 请参阅页面 here 上的相同问题
关于java - 如何使用 @Transactional 注释测试方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58442301/