【问题标题】:Cannot inject service into Spring test无法将服务注入 Spring 测试
【发布时间】:2017-01-29 14:00:26
【问题描述】:

financialReportService 在 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 的自定义数据库查询。

【问题讨论】:

    标签: java spring testing junit jhipster


    【解决方案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();
    

    【讨论】:

      猜你喜欢
      • 2016-05-29
      • 2021-05-04
      • 1970-01-01
      • 2023-01-15
      • 1970-01-01
      • 1970-01-01
      • 2017-10-30
      • 2017-06-27
      • 2018-07-27
      相关资源
      最近更新 更多