0

I'm using Spring Data JPA domain event as described in https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#core.domain-events. The event listener is marked with @Service. It is working perfectly when I run it, but I can't make it works when testing it using @DataJpaTest. If I replaced this with @SpringBootTest, the test run perfectly.

I know that @DataJpaTest will not load @Service. But even if I add @Import(MyService.class), this will still not work. My question how do I test domain event with @DataJpaTest without loading the full context as in @SpringBootTest?

a20_umb
  • 23
  • 1
  • 5

2 Answers2

0

It turned out that @SpringBootTest added @Transactional to the test. This causes the domain event listener to be not executed since it is still in transaction.

a20_umb
  • 23
  • 1
  • 5
0

This is my solution.

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

}
Dharman
  • 30,962
  • 25
  • 85
  • 135