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)
我更喜欢相反的方法,这是更多的集成 test-ey:
ApplicationListener使用 MockitoConfigurableApplicationContext使用这种方法,您可以测试某个事件是否已通过有人接收它的方式发布。
这是基本身份验证测试的代码。除其他条件外,我测试是否发生了登录事件
@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 的力量来深入验证事件参数。就我而言,我将代码扩展为:
| 归档时间: |
|
| 查看次数: |
4450 次 |
| 最近记录: |