java - 如何使用 @Transactional 注释测试方法

标签 java spring hibernate junit transactions

上下文

我正在测试带有 @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/

相关文章:

java - webflow测试,找不到流量模型

java - Hibernate异常org.hibernate.PropertyValueException : not-null property references a null or transient value

java - 带有枚举的 JPA 2 Criteria API

java - 将对象添加到 ListView - ANDROID

java - 使用 websocket javascript 客户端发送文件

java - 如何在多个变量上应用单个注释?

java - 如何在启动时以编程方式将 spring bean 标记为@Primary?

java - 如何在 Hibernate 中为具有可为空列的表构建类?

java - 哈希表中的空对象

java - 在没有 arrayList 的情况下向数组添加元素