通过基准中的注释加载应用程序上下文

时间:2016-10-11 06:52:15

标签: java spring unit-testing spring-mvc annotations

我们假设我想为benchmark类编写autowired,因此我需要加载application context

我的测试有注释@org.openjdk.jmh.annotations.State(Scope.Benchmark)和主要方法

public static void main(String[] args) throws RunnerException {
        Options opt = new OptionsBuilder()
                .include(MyBenchmark.class.getSimpleName())
                .forks(1)
                .build();

        new Runner(opt).run();
    }

当然,我有一些像这样的基准:

@Benchmark
public void countAllObjects() {
    Assert.assertEquals(OBJECT_COUNT, myAutowiredService.count());
}

现在,问题是如何注入myAutowiredService

可能的解决方案

@Setup方法中手动加载上下文。

ApplicationContext context = new ClassPathXmlApplicationContext("META-INF/application-context.xml");
context.getAutowireCapableBeanFactory().autowireBean(this);

但我不喜欢这个解决方案。我希望我的测试只有注释

@ContextConfiguration(locations = { "classpath:META-INF/application-context.xml" })

然后我只注射我的bean

@Autowired
private MyAutowiredService myAutowiredService;

但这不起作用。我认为,原因是我的测试应该使用Spring运行 no 注释:

@RunWith(SpringJUnit4ClassRunner.class)

但是没有必要这样做,因为我也没有任何@Test注释方法,因此我会得到No runnable methods例外。

在这种情况下,我是否可以通过注释加载上下文?

3 个答案:

答案 0 :(得分:1)

我从spring-cloud-sleuth找到了代码,对我有用

<div class="ny-search-input">
    <form id="ny-search-form" action="https://pubject.com/project/">
      <input style="width:100%" placeholder="Search Projects.." type="search" name="s" value="">
      <input type="hidden" name="cat" value="">
      <input type="hidden" name="loc" value="">
      <button><i class="search_link icon-search-light"></i></button>
    </form>
  </div>

答案 1 :(得分:0)

我会选择您已经草拟的getAutowireCapableBeanFactory().autowire()解决方案。

必须有一些样板代码加载应用程序上下文并触发自动装配。如果您希望使用注释指定应用程序配置,则安装方法可能如下所示:

AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.register(MyBenchmarkWithConfig.class);
context.refresh();

答案 2 :(得分:0)

@State(Scope.Benchmark)
public static class SpringState {

    AnnotationConfigApplicationContext config;

    @Setup
    public void setup() {
        context = new AnnotationConfigApplicationContext();
        context.register(CLASSNAME.class);
        context.register(ANOTHER_CLASSNAME_TO_BE_LOADED.class);
        context.refresh();
    }
}
相关问题