NPE在春天autowires窗体TestExecutionListener
这可能是错误的编码,但任何想法如何应该被赞赏。NPE在春天autowires窗体TestExecutionListener
我有这个类TestClass
需要注入很多服务类。由于我不能在@Autowired
对象上使用@BeforeClass
,因此我使用AbstractTestExecutionListener
。一切都按预期工作,但当我在@Test
块,所有对象评估null
。
任何想法如何解决这个问题?
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { ProjectConfig.class })
@TestExecutionListeners({ TestClass.class })
public class TestClass extends AbstractTestExecutionListener {
@Autowired private FirstService firstService;
// ... other services
// objects needs to initialise on beforeTestClass and afterTestClass
private First first;
// ...
// objects needs to be initialised on beforeTestMethod and afterTestMethod
private Third third;
// ...
@Override public void beforeTestClass(TestContext testContext) throws Exception {
testContext.getApplicationContext().getAutowireCapableBeanFactory().autowireBean(this);
first = firstService.setUp();
}
@Override public void beforeTestMethod(TestContext testContext) throws Exception {
third = thirdService.setup();
}
@Test public void testOne() {
first = someLogicHelper.recompute(first);
// ...
}
// other tests
@Override public void afterTestMethod(TestContext testContext) throws Exception {
thirdService.tearDown(third);
}
@Override public void afterTestClass(TestContext testContext) throws Exception {
firstService.tearDown(first);
}
}
@Service
public class FirstService {
// logic
}
对于初学者来说,让您的测试课程AbstractTestExecutionListener
不是一个好主意。 A TestExecutionListener
应该在独立课堂上实施。所以你可能想重新考虑这种方法。
在任何情况下,当前的配置被打破:禁用了所有默认TestExecutionListener
实现。
要包含默认值,请改为尝试以下配置。
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = ProjectConfig.class)
@TestExecutionListeners(listeners = TestClass.class, mergeMode = MERGE_WITH_DEFAULTS)
public class TestClass extends AbstractTestExecutionListener {
// ...
}
问候,
山姆
我正在考虑将'AbstractTestExecutionListener'移动到一个独立的类/ es。不过,我只是不知道如何访问的每个'@ TestClass'的'Test'没有坚持到任何数据库 –
这个答案只有解决了运行时的每个阶段('beforeTestClass'和'beforeTestMethod')创建的对象'@ Autowired'全局变量的'null'。 'beforeTestClass'和'beforeTestMethod'期间初始化的全局变量在'@ Test'方法下仍然评估为'null'。 –
(春季TestContext框架作者)确保,服务你自动布线已经标注了**斯特里奥型注释** –
所有服务正在使用'org.springframework.stereotype.Service'注释。 –