2014-04-26 5 views
0

@ContextConfiguration (...) @Autowired가 자동으로 작동하고 Java 응용 프로그램을 실행할 때 스프링 테스트를 실행할 때 NullPointerException이 발생하는 이유는 무엇입니까? 다음의 예와스프링 테스트/프로덕션 응용 프로그램 컨텍스트

내가 얻을 NullPointerException이 :

public class FinalTest { 

    @Autowired 
    private App app; 

    public FinalTest() { 
    } 

    public App getApp() { 
     return app; 
    } 

    public void setApp(App app) { 
     this.app = app; 
    } 

    public static void main(String[] args) { 

     ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); 

     FinalTest finalTest = new FinalTest(); 
     finalTest.getApp().getCar().print(); 
     finalTest.getApp().getCar().getWheel().print(); 
    } 
} 

다음 예제와 함께 작동 :

context.getBean()를 수행의 필요, 그냥 @Autowired와 함께 작동하지 테스트에서
public class FinalTest { 

    private App app; 

    public FinalTest() { 
    } 

    public App getApp() { 
     return app; 
    } 

    public void setApp(App app) { 
     this.app = app; 
    } 

    public static void main(String[] args) { 

     ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); 

     FinalTest finalTest = new FinalTest(); 
     finalTest.setApp((App)context.getBean("app")); 
     finalTest.getApp().getCar().print(); 
     finalTest.getApp().getCar().getWheel().print(); 
    } 
} 

:

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(locations={"/applicationContext-test.xml"}) 
public class AppTest{ 

    @Autowired 
    private App app; 

    @Test 
    public void test(){ 

     assertEquals("This is a SEAT_test car.", this.app.getCar().toString()); 
     assertEquals("This is a 10_test wheel.", this.app.getCar().getWheel().toString()); 
    } 
} 

감사합니다.

+0

비 테스트 환경에서'@ Autowired '로 할 수 있습니다. 자신이하는 일에 더 많은 맥락을 부여하십시오. –

+0

그것은 당신이하려는 일에 달려 있습니다. 모든 사람들이 당신이하려는 일에 대해 명확한 시각을 갖기 위해 더 많은 코드를 보여주십시오. – geoand

답변

2

언제든지 @Autowired을 사용할 때마다 종속성이 삽입 될 클래스를 Spring에서 관리해야합니다.

와 시험 :

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(locations={"/applicationContext-test.xml"}) 

는 스프링에 의해 관리됩니다. 어노테이션이 존재하지 않으면, 클래스는 스프링에 의해 관리되지 않으므로 의존성 삽입이 수행됩니다.

+0

이제는 Spring에서 관리하는 테스트의 요지를 이해합니다. 고마워요! – David

+0

@David 문제가 없습니다! – geoand

0

당신은 Spring이 관리하지 않는 인스턴스에 빈을 주입 할 것으로 기대하고 있습니다.

수동

FinalTest finalTest = new FinalTest(); 

봄은 자신이 관리하는 객체로 콩을 삽입 할 수 개체를 만드는 것입니다. 여기에서 Spring은 위에 생성 된 객체와 아무런 관련이 없습니다.

컨텍스트에서 FinalTest bean을 선언하고 검색하십시오. 구성이 맞으면 자동 실행됩니다.

+0

그래, 이해할 수 있지만 테스트가 가능한 이유는 무엇입니까? 테스트가 Spring에서 관리하는 객체이기 때문에 그렇습니까? – David

+0

@David 이것은 테스트와는 아무런 관련이 없습니다. 그것은 당신의 구성과 관련이 있습니다. 테스트에서 Spring은 테스트 클래스를위한 bean을 생성합니다. 그 bean을 관리하기 때문에'App' bean을 autowire 할 수있다. 'FinalTest' 타입의 bean을 선언했다면 똑같이 할 수 있습니다. –

+0

나는 완전히 이해하고있다. 당신의 설명에 대해 고마워요! – David

관련 문제