Mockito Spring Camel @Autowire fail

谁说胖子不能爱 提交于 2019-12-11 21:22:00

问题


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!
//...

回答1:


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;
}



来源:https://stackoverflow.com/questions/51163123/mockito-spring-camel-autowire-fail

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!