【问题标题】:How to test domain event in Spring Boot @DataJpaTest?如何在 Spring Boot @DataJpaTest 中测试域事件?
【发布时间】:2018-01-25 13:34:35
【问题描述】:

我正在使用 https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#core.domain-events 中描述的 Spring Data JPA 域事件。事件侦听器标有@Service。当我运行它时它工作得很好,但是在使用@DataJpaTest 测试它时我不能让它工作。如果我将其替换为@SpringBootTest,则测试运行完美。

我知道@DataJpaTest 不会加载@Service。但即使我添加@Import(MyService.class),这仍然行不通。我的问题是如何使用@DataJpaTest 测试域事件而不像@SpringBootTest 那样加载完整的上下文?

【问题讨论】:

    标签: spring-boot spring-data-jpa spring-boot-test


    【解决方案1】:

    原来@SpringBootTest 在测试中添加了@Transactional。这会导致域事件侦听器未执行,因为它仍在事务中。

    【讨论】:

      【解决方案2】:

      这是我的解决方案。

      // TestConfig
      @TestConfiguration
      public class TestConfig {
      
        @Bean
        public MyService myService() {
          return new MyService()
        }
      
      }
      
      // Domain Event Test
      @RunWith(SpringRunner.class)
      @Import({TestConfig.class})
      @Transactional
      @DataJpaTest
      public class DomainEventTest {
      
        @Autowired
        private TestRepository repository;
      
        public void domainEventTest() {
          Entity entity = new Entity();
          repository.save(entity);
        }
      
      }
      

      【讨论】:

        猜你喜欢
        • 2019-03-28
        • 2018-10-26
        • 2017-05-31
        • 2018-03-01
        • 2020-08-13
        • 2021-03-16
        • 2022-12-29
        • 2019-03-30
        • 2019-01-18
        相关资源
        最近更新 更多