2017-10-13 5 views
1

이 코드는 잘못 코딩되었을 수 있지만 어떻게 수행해야하는지 생각해보십시오.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 
} 
+0

(스프링 TestContext 프레임 워크의 저자) ** –

+0

모든 서비스는'org.springframework.stereotype.Service' 주석을 사용하고 있습니다. –

답변

3

우선 테스트 클래스를 구현하는 경우 AbstractTestExecutionListener을 구현하는 것은 좋지 않습니다. TestExecutionListener은 독립 실행 형 클래스로 구현해야합니다. 그래서 당신은 그 접근법을 다시 생각하고 싶을지도 모릅니다.

어쨌든 현재 구성이 깨졌습니다. 모든 기본 TestExecutionListener 구현을 사용 중지했습니다.

기본값을 포함하려면 대신 다음 구성을 시도하십시오.

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(classes = ProjectConfig.class) 
@TestExecutionListeners(listeners = TestClass.class, mergeMode = MERGE_WITH_DEFAULTS) 
public class TestClass extends AbstractTestExecutionListener { 
    // ... 
} 

감사합니다,

샘이 자동 배선 ** Sterio 형 - 주석 주석가 있는지, 서비스를 확인

+0

'AbstractTestExecutionListener'를 독립 실행 형 클래스/es로 옮길 것을 고려하고 있습니다. 그러나 모든 데이터베이스에 유지하지 않고'TestClass'의 각'@ Test '런타임에 각 단계 ('beforeTestClass'와'beforeTestMethod')에서 생성 된 객체에 액세스하는 방법을 모르겠습니다. –

+0

이 대답 만 해결되었습니다. '@ Autowired' 전역 변수의'null '. 'beforeTestClass'와'beforeTestMethod' 동안 초기화 된 전역 변수는 여전히'@ Test' 메소드/s 하에서'null'으로 평가됩니다. –