简体   繁体   English

Mockito弹簧骆驼@Autowire失败

[英]Mockito Spring Camel @Autowire fail

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). 被测试的路由扩展了一个自定义的抽象RouteBuilder(我知道关于继承优先于继承-这是维护代码)。 I've set up my test as @Roman Vottner did over here . 我已经像@Roman Vottner 在这里所做的那样设置了测试。 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. 它具有一个@Autowired类,即使在测试开始时对其进行了模拟和@Autowired,该类也尚未初始化(为null)。 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: 通过显式地将FooRoute声明为bean来解决此问题:

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

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

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM