2017-03-29 52 views
3

我嘗試將junit測試寫入我的服務。 我在我的項目spring-boot 1.5.1中使用。一切工作正常,但當我嘗試自動裝配bean(在AppConfig.class中創建)時,它給了我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

Ofcourse你的依賴將是null,由於@InjectMocks要創建一個新的實例,春天的知名度外因此沒有什麼會自動連線。

Spring Boot具有廣泛的測試支持,也可用於替換豆類,參見Spring Boot參考指南的the testing section

解決它與框架而不是周圍的工作。

  1. 更換@Mock@MockBean
  2. @Autowired
  3. 更換@InjectMocks刪除你的設置方法

顯然也只需要一個模擬的SOAP存根(所以不知道你需要模擬什麼對於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