Search code examples
javaspring-bootunit-testingjunitmockito

Facing java.lang.ClassCastException while writing tests for a method that requires to map Object to List


I am writing unit-test for the below Class using Mockito:

public class ExternalQueryBuilder {

    public String buildQuery(Map<String, Object> request) {
        StringBuilder queryBuilder = new StringBuilder();

        if (request.containsKey("dataElement") && request.get("dataElement") != null) {
            queryBuilder.append("&Data Element=").append(request.get("dataElement"));
        }

        log.info(String.valueOf(request.get("dataSourceType")));

        if (request.containsKey("dataSourceType")) {
            List<String> dataSourceType = (List<String>) request.get("dataSourceType");
            if(dataSourceType.size() > 0)
                queryBuilder.append("&Data Source Type=").append(dataSourceType.get(0).replace("&", "\\&"));
        }
}
}

As you can see in this method, there is one line inside if (request.containsKey("dataSourceType")) which is List<String> dataSourceType = (List<String>) request.get("dataSourceType"); doing this casting of whatever data coming from request.get("dataSourceType");. In this line I am getting this error java.lang.ClassCastException: class java.lang.Object cannot be cast to class java.util.List (java.lang.Object and java.util.List are in module java.base of loader 'bootstrap')

Now my test code is:

    public void buildQueryTest(){
        StringBuilder queryBuilder = Mockito.mock(StringBuilder.class);
        Object obj = Mockito.mock(Object.class);
        Map<String, Object> request = new HashMap<>();
        request.put("dataElement",obj);
        request.put("dataSourceType",obj);
        externalQueryBuilder.buildQuery(request);
    }

In this code I am initialising request with type Map<String, Object> since in the above Class method that I m testing the type of request is Map<String, Object> only.

Then at the end I am calling the actual method externalQueryBuilder.buildQuery(request); where externalQueryBuilder is the object of the class I am mocking.This line will call the actual method and when I reach to line List<String> dataSourceType = (List<String>) request.get("dataSourceType"); it throws the Classcast error in actual method. I need some help with that. Please provide some suggestions to resolve it.I am new to both Java and Mockito.


Solution

  • you can not assign object to list like

    List<String> dataSourceType = (List<String>) request.get("dataSourceType");
    
    

    assign it to object having list

    Object obj = request.get("dataSourceType");
    
    

    Object obj can be custom Object with List property which can be obtained as obj.getListProperty check on feasibility of gettting list from obj