【问题标题】:How tests methods with @Transactional anotation如何使用 @Transactional 注释测试方法
【发布时间】:2020-02-14 22:42:23
【问题描述】:

上下文

我正在使用@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 方法调用它时,它不会保留任何东西。

当我从目标方法中删除 de @Transactional 注释时,一切正常,并且在测试中保持正常。

当我运行测试时,数据库在内存中,我使用迁移 flyway、mysql、spring、hirbernate、springboot。

问题

我可以在运行测试时配置 @Transactional 注释以排除它吗?

谢谢。

【问题讨论】:

    标签: java spring hibernate junit transactions


    【解决方案1】:

    您可以轻松使用@Rollback(false) 注释。 在here页面上查看相同的问题

    【讨论】:

    • 谢谢,我会添加@Rollback(false)注解。
    猜你喜欢
    • 2018-02-23
    • 2019-07-12
    • 2020-03-29
    • 2012-04-04
    • 2019-11-18
    • 2011-09-07
    • 2012-08-25
    • 2019-07-14
    相关资源
    最近更新 更多