【发布时间】:2023-03-08 06:16:02
【问题描述】:
假设我想为可以是autowired 的类写一个benchmark,因此我需要加载application context。
我的测试有注解@org.openjdk.jmh.annotations.State(Scope.Benchmark)和main方法
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;
但这不起作用。我认为原因是我有 no 注释,我的测试应该使用 Spring 运行:
@RunWith(SpringJUnit4ClassRunner.class)
但是这样做没有意义,因为我也没有任何 @Test 注释方法,因此我会得到 No runnable methods 异常。
这种情况下能否通过注解实现上下文加载?
【问题讨论】:
-
您找到解决方案了吗?
标签: java spring unit-testing spring-mvc annotations