简体   繁体   中英

Junit test java.lang.NullPointerException for Map<String, List<String>>

I'm trying to unit test a class having the following function:

  private String getTabSeparateValues(final QueryParams params, final HttpServletRequest request) {
        MetricsSerializer serializer = new MetricsSerializer();
        return serializer.serializeValues(params, request);
    }

It calls the "serializeValues(params,request)" function in the following class:

public class MetricsSerializer {

    private final StringJoiner stringJoiner = new StringJoiner("\t");
    private static final String MONTH_FORMAT = "MMMMM";

      public String serializeMetrics(final QueryParams queryParams, final HttpServletRequest request) {
        addValueFromString(queryParams.getId());
        addValueFromString(getCurrentMonth());
        addValueFromString(request.getRemoteUser().split("@")[0]);
        addValueFromString(queryParams.getCurrency());
        addValuesFromList(queryParams.getCompanies());
        addValueFromString(queryParams.getCognosDatasetType());
        addValuesFromList(queryParams.getScenarios());
        addFilter(queryParams.getFilters());
        addGroupings(queryParams.getGroupings());
        addValueFromString(queryParams.getReportTemplate());
        return stringJoiner.toString();
    }

    private void addValueFromString(final String value) {
        stringJoiner.add(value);
    }

    private void addFilter(final List<Map<String, List<String>>> filters) {
        List<String> collect = filters.stream()
                .flatMap(entry -> entry.keySet()
                        .stream())
                .collect(Collectors.toList());
        addValuesFromList(collect);
    }

    private void addGroupings(final Map<String, List<String>> groupings) {
        addValuesFromList(new ArrayList<>(groupings.keySet()));
    }

    private void addValuesFromList(final List<String> listValues) {
        stringJoiner.add(listValues.stream().collect(Collectors.joining(" ")));
    }

    private String getCurrentMonth() {
        DateFormat monthFormat = new SimpleDateFormat(MONTH_FORMAT);
        return monthFormat.format(new Date());
    }

}

This class returns the values in a tab-separated format. The structure of the QueryParams class is as follows:

@Data
@Builder
public class QueryParams {
    private String datasetType;
    private Map<String, List<String>> groupings;
    private List<Aggregate> aggregates;
    private List<String> scenarios;
    private List<String> companies;
    private List<Map<String, List<String>>> filters;
    private List<NamedTimeRange> timeRanges;
    private Map<String, String> params;
    private String reportTemplate;
    private String id;
    private String currency;
}

I am not using all of the parameters in the QueryParameters (Skipping timeranges, params, aggregates). In order to test if I'm actually getting tab-separated metrics, I wrote the following test:

public class MetricsHandlerTest {

    private QueryParams queryParams;

    @Before
    public void setUp() throws Exception {
        List<String> list = Arrays.asList("one", "two");
        List<String> scenarioList = Arrays.asList("A1");
    List<Map<String, List<String>>> filter = new ArrayList<>();
    Map<String, List<String>> filtersMap = new HashMap<>();
    List<String> filterList = Arrays.asList("COM");
    filtersMap.put("product", filterList);
    filter.add(filtersMap);
        queryParams = QueryParams.builder()
                .id("123").currency("USD").companies(list).scenarios(scenarioList).filters(filter)
                .build();
    }

    @Test
    public void tabSerializerTest() {
        String remoteUser = "testuser";
        HttpServletRequest httpServletRequest = Mockito.mock(HttpServletRequest.class);
        Mockito.when(httpServletRequest.getRemoteUser())
                .thenReturn(remoteUser);
        MetricsSerializer metricsSerializer = new MetricsSerializer();
        String tabs = metricsSerializer.serializeMetrics(queryParams, httpServletRequest);
        assertEquals(tabs, "123 \t USD \t one two");
    }
}

I'm getting a null pointer exception for groupings. (in "addGroupings" of MetricsSerializer class) I tried logging groupings and it can be null. For scenarios and filters, I have added values. How do I handle this for groupings where it can be null? Any help regarding how to fix this would be greatly appreciated.

I am not sure if I understand your issue. Is MetricsSerializer under your control? If so then you need to make it defensive to have null check to handle the case where groupings is null.

If it is outside of your control, then you need to build your query with an empty Group(rather than null) like this

queryParams = QueryParams.builder().withGroupings(new HashMap<String,List<String>>()).build();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM