How to test Spring @EventListener method?

前端 未结 3 862
遇见更好的自我
遇见更好的自我 2021-01-11 23:04

I have some event publishing:

@Autowired private final ApplicationEventPublisher publisher;
...
publisher.publishEvent(new MyApplicationEvent(mySource));
         


        
3条回答
  •  情深已故
    2021-01-11 23:58

    First, As you're using Spring Boot, the testing of these becomes pretty straightforward. This test will spin up the boot context and inject a real instance of ApplicationEventPublisher, but create a mocked instance of SomeDependency. The test publishes the desired event, and verifies that your mock was invoked as you expected.

    @RunWith(SpringRunner.class)
    @SpringBootTest
    public class EventPublisherTest {
    
       @Autowired 
       private final ApplicationEventPublisher publisher;
    
       @MockBean
       private SomeDependency someDependency;
    
       @Test
       public void test() {
          publisher.publishEvent(new MyApplicationEvent(createMySource()));
    
          // verify that your method in you 
          verify(someDependency, times(1)).someMethod();
       }
    }
    

提交回复
热议问题