如何使用Spring、JUnit和Mockito验证事件是否已发布?

如何使用Spring、JUnit和Mockito验证事件是否已发布?,spring,events,junit,mockito,spring-4,Spring,Events,Junit,Mockito,Spring 4,我将Spring4.3.8.RELEASE与JUnit4.12和Mockito1.10.18一起使用。我有一个发布事件的服务 @Service("organizationService") @Transactional public class OrganizationServiceImpl implements OrganizationService, ApplicationEventPublisherAware publisher.publishEvent(new

我将Spring4.3.8.RELEASE与JUnit4.12和Mockito1.10.18一起使用。我有一个发布事件的服务

@Service("organizationService")
@Transactional
public class OrganizationServiceImpl implements OrganizationService, ApplicationEventPublisherAware

            publisher.publishEvent(new ZincOrganizationEvent(id));

    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher publisher) 
    {
        this.publisher = publisher;
    }

    ...
    @Override
    public void save(Organization organization)
    {
    ...
    publisher.publishEvent(new ThirdPartyEvent(organization.getId()));
我的问题是,如何在JUnit测试中验证事件是否已实际发布

@Test
public void testUpdate()
{

m_orgSvc.save(org);
// Want to verify event publishing here

如果您想测试您是否忘记在
OrganizationServiceImpl
中调用
publishEvent
方法,您可以使用以下方法:

class OrganizationServiceImplTest {

    private OrganizationServiceImpl organizationService;

    private ApplicationEventPublisher eventPublisher;

    @Before
    public void setUp() {
        eventPublisher = mock(ApplicationEventPublisher.class);

        organizationService = new OrganizationServiceImpl();
        organizationService.setApplicationEventPublisher(eventPublisher)
    }

    @Test
    public void testSave() {

        /* ... */

        organizationService.save(organization);

        verify(eventPublisher).publishEvent(any(ThirdPartyEvent.class));
    }

}
上面的测试用例将验证是否调用了
publishEvent
方法

更多

关于:

我的问题是,如何在JUnit测试中验证事件是否已实际发布


如果要验证实际发送,您必须测试应用程序EventPublisher的实现,并且可能不需要模拟。

我更喜欢相反的方法,这是更为集成的测试:


  • 您的意思是在@Before方法中编写“ApplicationEventPublisher eventPublisher”吗?amkes将模拟实例本地化为before方法,因此在测试中方法字段“eventPublisher”仍然为null,除非“我误读了一些东西。对于大多数上下文配置,相同的方法可用于
    @Autowired ApplicationEventMulticaster
    ,另外,当测试之间共享Spring上下文时,可以在
    @TearDown
    中取消注册侦听器,这可能很有用。”