创建模拟对象时出现空指针异常

时间:2018-10-18 10:51:53

标签: java junit mockito

我是Junit的新手。请在下面的代码中提出问题所在:-

Mockito.when(daoimpl.getEcgs(request)).thenReturn(listOfecg);

getEcgs()接受DashboardRequest对象和POJO(如果此类为-:

public String eligibilityCarrierGroupId;
public Set<String> carrierIds;
@LastModifiedDate
public Date fromDate;
@LastModifiedDate
public Date toDate;

并且listOfecg POJO是

private String ecgId;
private List<String> carrier;

现在,考虑到我正在为每个字段设置一些值,即使在那之后,我在

上获取了空指针异常
Mockito.when(daoimpl.getEcgs(request)).thenReturn(listOfecg);

请告知我可能出了什么问题。

完整代码-:

public class DashboardDataServiceTest {

    //Set<String> testSet = new HashSet<String>();

    private MockMvc mockMvc;
    @Mock
    private DashboardService dashboardService;
    @InjectMocks
    private DashboardDataController dashboardController;
    @InjectMocks
    DashboardDaoImpl daoimpl= new DashboardDaoImpl();

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
        this.mockMvc = MockMvcBuilders.standaloneSetup(dashboardController).build();
    }

    @Test
    public void testDashboardInfo() throws Exception {
        DashboardRequest request = new DashboardRequest();

        DashboardDataResponse response = new DashboardDataResponse();
        List<String> carrierIds = new ArrayList<>();
        Set<String> testSet = new HashSet<String>();
        carrierIds.add("KCY");
        List<DashboardStatusCount> overall = new ArrayList<>();
        DashboardStatusCount dashstatus = new DashboardStatusCount();
        dashstatus.setStatus("Success");
        dashstatus.setCount(12);
        overall.add(dashstatus);

        request.setEligibilityCarrierGroupId("aaa");
        testSet.add("KCY");
        request.setCarrierIds(testSet);
        request.setFromDate(new Date());
        request.setToDate(new Date());
        response.setOverallTotals(271);
        response.setOverall(overall);
        List<EligibilityCarrierGroupingDoc> listOfecg = new ArrayList<>();
        List<String> carrierIdsx = new ArrayList<>();
        EligibilityCarrierGroupingDoc ecgDoc = new EligibilityCarrierGroupingDoc();
        ecgDoc.setEcgId("aaa");
        carrierIdsx.add("KCY");

        ecgDoc.setCarrier(carrierIdsx);
        listOfecg.add(ecgDoc);

        Mockito.when(daoimpl.getEcgs(request)).thenReturn(listOfecg);

        DashboardDataResponse responsedata = dashboardService.getDashBoardResponseData(request);
        System.out.println("The response data is "+responsedata);
    }
    private String mapToJson(Object object) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        return objectMapper.writeValueAsString(object);
    }
}

谢谢。

0 个答案:

没有答案