Let's assume I want to write a benchmark
for the class which can be autowired
thus I need to load application context
.
My test has annotation @org.openjdk.jmh.annotations.State(Scope.Benchmark)
and main method
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.include(MyBenchmark.class.getSimpleName())
.forks(1)
.build();
new Runner(opt).run();
}
And of course I have some benchmarks like this:
@Benchmark
public void countAllObjects() {
Assert.assertEquals(OBJECT_COUNT, myAutowiredService.count());
}
Now, the question is how do I inject myAutowiredService
?
Possible solution
Load manually the context in @Setup
method.
ApplicationContext context = new ClassPathXmlApplicationContext("META-INF/application-context.xml");
context.getAutowireCapableBeanFactory().autowireBean(this);
But I don't like this solution. I would prefer that my test just have annotation
@ContextConfiguration(locations = { "classpath:META-INF/application-context.xml" })
and then I just inject my bean like
@Autowired
private MyAutowiredService myAutowiredService;
but this does not work. The reason, I assume, is that I have no annotation that my test should run with Spring:
@RunWith(SpringJUnit4ClassRunner.class)
However there is no point of doing this because I also don't have any @Test
annotated methods, thus I will get No runnable methods
exception.
Can I achieve loading the context via annotations in this case?