简体   繁体   English

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

[英]How tests methods with @Transactional anotation

Context语境

I am testing a method with @Transactional anotation.我正在使用@Transactional 注释测试一种方法。

Tested Method inside Business class业务内部测试方法 class

@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);
}

Unit Test单元测试

@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()
  }

Problem问题

When I call it from the @Test method, it doesn't persist anything.当我从 @Test 方法调用它时,它不会保留任何东西。

When I remove de @Transactional anotation from the target method all works fine and persist ok from the test.当我从目标方法中删除 de @Transactional 注释时,一切正常,并且在测试中保持正常。

The database is in memory when I run the tests and I use migrations flyway, mysql, spring, hirbernate, springboot.当我运行测试时,数据库位于 memory 中,我使用迁移 flyway、mysql、spring、hirbernate、springboot。

Question问题

Can I configure @Transactional anotation for exclude it when I run the tests?我可以在运行测试时配置 @Transactional 注释以排除它吗?

Thanks.谢谢。

you can easily use @Rollback(false) annotation.您可以轻松使用 @Rollback(false) 注释。 see the same question on page here此处的页面上查看相同的问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM