Java 弹簧autowires表单测试仪上的NPE执行侦听器
这可能是错误的编码,但任何关于如何做到这一点的想法都是值得赞赏的Java 弹簧autowires表单测试仪上的NPE执行侦听器,java,spring,unit-testing,junit4,spring-test,Java,Spring,Unit Testing,Junit4,Spring Test,这可能是错误的编码,但任何关于如何做到这一点的想法都是值得赞赏的 我有一个类TestClass,它需要注入许多服务类。因为我不能在@Autowired对象上使用@BeforeClass,所以我使用了AbstractTestExecutionListener。一切正常,但当我在@Test块上时,所有对象都被计算null 你知道怎么解决这个问题吗 @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { Pr
我有一个类
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不是一个好主意。
TestExecutionListener
应该在独立类中实现。因此,您可能需要重新考虑这种方法
在任何情况下,您当前的配置都会被破坏:您禁用了所有默认的TestExecutionListener
实现
要包含默认值,请尝试以下配置
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=ProjectConfig.class)
@TestExecutionListeners(listeners=TestClass.class,mergeMode=MERGE_,带有_默认值)
公共类TestClass扩展了AbstractTestExecutionListener{
// ...
}
问候,
Sam(SpringTestContext框架的作者)确保您正在自动连接的服务已经用Sterio类型的注释进行了注释。所有服务都使用
org.springframework.stereotype.Service
注释。我正在考虑将AbstractTestExecutionListener
移动到一个独立类/es。然而,我只是不知道如何在TestClass
的每个@Test
的运行时访问在每个阶段(beforeTestClass
和beforeTestMethod
)上创建的对象,而不保存到任何数据库。这个答案只解决了@Autowired
全局变量的null
。在beforeTestClass
和beforeTestMethod
期间初始化的全局变量仍然在@Test
方法/s下计算null
。