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

Dav*_*ave 2 events junit spring mockito spring-4

我将 Spring 4.3.8.RELEASE 与 JUnit 4.12 和 Mockito 1.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()));
Run Code Online (Sandbox Code Playgroud)

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

@Test
public void testUpdate()
{

m_orgSvc.save(org);
// Want to verify event publishing here
Run Code Online (Sandbox Code Playgroud)

usr*_*ΛΩΝ 6

我更喜欢相反的方法,这是更多的集成 test-ey

  • ???模拟ApplicationListener使用 Mockito
  • 将模拟应用程序侦听器注册到 ConfigurableApplicationContext
  • 做工作
  • ?验证模拟是否已收到事件

使用这种方法,您可以测试某个事件是否已通过有人接收它的方式发布。

这是基本身份验证测试的代码。除其他条件外,我测试是否发生了登录事件

@Test
public void testX509Authentication() throws Exception
{
    ApplicationListener<UserLoginEvent> loginListener = mock(ApplicationListener.class);
    configurableApplicationContext.addApplicationListener(loginListener);

    getMockMvc().perform(get("/").with(x509(getDemoCrt())))//
                .andExpect(status().is3xxRedirection())//
                .andExpect(redirectedUrlPattern("/secure/**"));

    getErrorCollector().checkSucceeds(() -> {
        verify(loginListener, atLeastOnce()).onApplicationEvent(any(UserLoginEvent.class));
        return null;
    });
}
Run Code Online (Sandbox Code Playgroud)

我的建议是释放 Mockito 的力量来深入验证事件参数。就我而言,我将代码扩展为:

  • 检查登录事件中的用户名是否与经过身份验证的主体匹配
  • 在用户公然登录失败的情况下执行额外的测试,我会期待各种登录失败事件之一