2017-01-29 9 views
0

financialReportService имеет значение NULL в контроллере REST, что означает, что он не может впрыснуть.Нельзя вводить услугу в тест весны

Тест:

@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); 

На отдельной ноте, следующая часть теста выглядит странно. Вы дважды получаете финансовые отчеты. Этот файл является FindocResourceIntTest, поэтому я удаляю любые прямые вызовы financialReportService.

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

 Смежные вопросы

  • Нет связанных вопросов^_^