2017-03-29 7 views
3

내 서비스에 junit 테스트를 작성하려고합니다. 제 프로젝트에서 스프링 부트 1.5.1을 사용합니다. 모든 것이 잘 작동하지만 AppConfig.class에서 생성 된 bean을 autowire하려고하면 NullPointerException이 발생합니다. 나는 거의 모든 것을 시도했다.SpringBoot Junit bean autowire

이 내 구성 클래스입니다 :

@Configuration 
public class AppConfig { 

@Bean 
public DozerBeanMapper mapper(){ 
    DozerBeanMapper mapper = new DozerBeanMapper(); 
    mapper.setCustomFieldMapper(new CustomMapper()); 
    return mapper; 
} 
} 

내 테스트 클래스 :

@SpringBootTest 
public class LottoClientServiceImplTest { 
@Mock 
SoapServiceBindingStub soapServiceBindingStub; 
@Mock 
LottoClient lottoClient; 
@InjectMocks 
LottoClientServiceImpl lottoClientService; 
@Autowired 
DozerBeanMapper mapper; 

@Before 
public void setUp() throws Exception { 
    initMocks(this); 
    when(lottoClient.soapService()).thenReturn(soapServiceBindingStub); 
} 

@Test 
public void getLastResults() throws Exception { 

    RespLastWyniki expected = Fake.generateFakeLastWynikiResponse(); 
    when(lottoClient.soapService().getLastWyniki(anyString())).thenReturn(expected); 

    LastResults actual = lottoClientService.getLastResults(); 

수있는 사람이 잘못 뭔지 말해?

오류 로그 :

java.lang.NullPointerException 
at pl.lotto.service.LottoClientServiceImpl.getLastResults(LottoClientServiceImpl.java:26) 
at pl.lotto.service.LottoClientServiceImplTest.getLastResults(LottoClientServiceImplTest.java:45) 

이 내 서비스 :

@Service 
public class LottoClientServiceImpl implements LottoClientServiceInterface { 
@Autowired 
LottoClient lottoClient; 
@Autowired 
DozerBeanMapper mapper; 
@Override 
public LastResults getLastResults() { 
    try { 
     RespLastWyniki wyniki = lottoClient.soapService().getLastWyniki(new Date().toString()); 
     LastResults result = mapper.map(wyniki, LastResults.class); 
     return result; 
    } catch (RemoteException e) { 
     throw new GettingDataError(); 
    } 
} 
+0

오류 로그를 표시 할 수 있습니까? –

+0

방금 ​​추가했습니다 – franczez

+0

코드 26 줄을 표시해주세요. – dunni

답변

2

은 당연히 당신의 의존성으로 인해 @InjectMocks 새 인스턴스를 만들에, null 될 것입니다, 봄의 가시성 외부 그리고 아무것도 자동 배선되지 않습니다.

스프링 부트는 광범위한 테스트 지원을 제공하며 콩을 모의로 대체하기도합니다. 스프링 부트 참조 가이드 the testing section을 참조하십시오.

프레임 워크를 사용하지 않고 프레임 워크에서 수정하려면 수정하십시오.

는 또한 명백하게 만합니다 (SOAP 스텁 당신이 조롱 할 필요가 무엇인지 확신하지 모의을 필요로 당신의 설정 방법 제거 @Autowired

  • @InjectMocks 교체 @MockBean
  • @Mock 교체 에 대한 LottoClient).

    트릭을해야합니다.

    @SpringBootTest 
    public class LottoClientServiceImplTest { 
    
        @MockBean 
        SoapServiceBindingStub soapServiceBindingStub; 
    
        @Autowired 
        LottoClientServiceImpl lottoClientService; 
    
        @Test 
        public void getLastResults() throws Exception { 
    
         RespLastWyniki expected = Fake.generateFakeLastWynikiResponse(); 
         when(soapServiceBindingStub.getLastWyniki(anyString())).thenReturn(expected); 
    
         LastResults actual = lottoClientService.getLastResults(); 
    
  • +0

    , 고마워. – franczez

    관련 문제