이 코드는 잘못 코딩되었을 수 있지만 어떻게 수행해야하는지 생각해보십시오.Spring autowires 폼의 NPE TestExecutionListener
나는 많은 서비스 클래스를 주입해야하는이 클래스 TestClass
있습니다. @BeforeClass
을 @Autowired
개체에 사용할 수 없으므로 결과는 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
}
(스프링 TestContext 프레임 워크의 저자) ** –
모든 서비스는'org.springframework.stereotype.Service' 주석을 사용하고 있습니다. –