0

我正在使用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

4

2 回答 2

0

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

于 2017-08-18T05:18:39.393 回答
0

这是我的解决方案。

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

}
于 2020-08-05T05:54:25.653 回答