Mockito Spring Camel @Autowire 失败 [英] Mockito Spring Camel @Autowire fail

查看:23
本文介绍了Mockito Spring Camel @Autowire 失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对骆驼路线进行单元测试.被测路由扩展了一个自定义抽象 RouteBuilder(我知道偏向于组合而不是继承——这是维护代码).我已经像@Roman Vottner 一样设置了我的测试

I'm trying to unit test a camel route. The route under test extends a custom abstract RouteBuilder (I know about favouring composition over inheritance - this is maintenance code). I've set up my test as @Roman Vottner did over here. Everything works (is initialized) until I hit the first abstract class up the hierarchy. It has an @Autowired class which wasn't initialized (is null) even though it was mocked and @Autowired when the test started. Any ideas on how to solve my injection problem?

@RunWith(CamelSpringRunner.class)
@BootstrapWith(CamelTestContextBootstrapper.class)
@ContextConfiguration(loader = AnnotationConfigContextLoader.class, classes = {FooRouteTest.ContextConfig.class})
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS)
public class FooRouteTest {

  @Configuration
  @PropertySource({"classpath:some.properties", "classpath:environment.properties"})
  public static class ContextConfig extends CamelConfiguration {

    @Bean
    public UserServices userServices() {
      return mock(UserServices.class);
    } //and many more of the like
  }

  @Autowired
  private UserServices userServices; //and all the others too

  @Test
  public void testAfoo() throws Exception {
//....
    template.setDefaultEndpointUri("direct://getTheData");
    template.sendBody(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonNode));
//...
  }
}

in the abstract super class while debugging:

@Autowired
public ClientServices clientServices;
//...
String clientNumber=clientServices.getLoggedInNumber();  //clientServices is null and not mocked!
//...

解决方案

Solved this by explicitly declaring FooRoute as a bean:

@Bean
public FooRoute fooRoute(){
  return new FooRoute();
}

@Override
public List<RouteBuilder> routes() {
  final List<RouteBuilder> routes = new ArrayList<>();
  routes.add(fooRoute());
  return routes;
}

这篇关于Mockito Spring Camel @Autowire 失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆