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

Ruf*_*ufi 6 java spring unit-testing annotations spring-mvc

假设我想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();
    }
Run Code Online (Sandbox Code Playgroud)

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

@Benchmark
public void countAllObjects() {
    Assert.assertEquals(OBJECT_COUNT, myAutowiredService.count());
}
Run Code Online (Sandbox Code Playgroud)

现在的问题是如何注入myAutowiredService

可能的解决方案

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

ApplicationContext context = new ClassPathXmlApplicationContext("META-INF/application-context.xml");
context.getAutowireCapableBeanFactory().autowireBean(this);
Run Code Online (Sandbox Code Playgroud)

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

@ContextConfiguration(locations = { "classpath:META-INF/application-context.xml" })
Run Code Online (Sandbox Code Playgroud)

然后我就注入我的豆子

@Autowired
private MyAutowiredService myAutowiredService;
Run Code Online (Sandbox Code Playgroud)

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

@RunWith(SpringJUnit4ClassRunner.class)
Run Code Online (Sandbox Code Playgroud)

然而这样做是没有意义的,因为我也没有任何@Test带注释的方法,因此我会得到No runnable methods异常。

在这种情况下我可以通过注释实现加载上下文吗?

Fri*_*rdt 0

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

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

AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.register(MyBenchmarkWithConfig.class);
context.refresh();
Run Code Online (Sandbox Code Playgroud)