2017-01-29 2 views
0

financialReportServiceは、RESTコントローラでインジェクションに失敗したことを示すnullです。Springテストにサービスをインジェクトでき​​ません

試験:

@RunWith(SpringRunner.class) 
@SpringBootTest(classes = SnapshotfindocApp.class) 
public class FindocResourceIntTest { 
@Inject 
    private FinancialReportService financialReportService; 
@Before 
    public void setup() { 
     MockitoAnnotations.initMocks(this); 
     FindocResource findocResource = new FindocResource(); 
     ReflectionTestUtils.setField(findocResource, "findocRepository", findocRepository); 
     this.restFindocMockMvc = MockMvcBuilders.standaloneSetup(findocResource) 
      .setCustomArgumentResolvers(pageableArgumentResolver) 
      .setMessageConverters(jacksonMessageConverter).build(); 
    } 


@Test 
    @Transactional 
    public void getFinancialRecords() throws Exception { 

     // Get all the financial-reports 
     restFindocMockMvc.perform(get("/api/financial-reports")) 
      .andExpect(status().isOk()); 
     List<Findoc> finReports = financialReportService.getFinancialReports(); 
     for (Findoc fr : finReports) { 
      assertThat(fr.getNo_months()).isBetween(12, 18); 
      LocalDate documentTimeSpanLimit = LocalDate.now().minusMonths(18); 
      assertThat(fr.getFinancial_date()).isAfterOrEqualTo(documentTimeSpanLimit); 
     } 
    } 

サービス:

@Service 
@Transactional 
public class FinancialReportService { 

    private final Logger log = LoggerFactory.getLogger(FinancialReportService.class); 

    @Inject 
    private FinancialReportDAO financialReportDAO; 

    public List<Findoc> getFinancialReports(){ 
     return financialReportDAO.getFinancialReports(); 
    } 

} 

コントローラー:

@GetMapping("/financial-reports") 
    @Timed 
    public List<Findoc> getFinancialReports() { 
     log.debug("REST request to get financial records"); 
     return financialReportService.getFinancialReports(); // financialReportService is null 
    } 

更新:

アプリケーションはJHipsterによって生成されます。その後、new serviceとDAOファイルが追加され、カスタムデータベースクエリがH2に有効になりました。

答えて

1

@Injectサービスの後に、setup()メソッドでフィールドを設定する必要もあります。以下の行を追加すると、問題は解決されます。

ReflectionTestUtils.setField(findocResource, "financialReportService", financialReportService); 

別の注記では、次の部分が奇妙に見えます。あなたは財務報告書を2回取っています。このファイルはFindocResourceIntTestなので、financialReportServiceへの直接呼び出しはすべて削除します。

// Get all the financial-reports 
    restFindocMockMvc.perform(get("/api/financial-reports")) 
     .andExpect(status().isOk()); 
    List<Findoc> finReports = financialReportService.getFinancialReports(); 
関連する問題