Junit mockito when(..).thenReturn() throws NullPointerException

Viewed 55975

Can anyone explain me the below scenario
Code to be tested
UserTransaction.java

@Override
public ServiceResponse<User> get(String name) {
    ServiceResponse<User> response = new ServiceResponse<User>();
    List<Map<String, Object>> exp = new ArrayList<Map<String, Object>>();
    Map<String, Object> map = new HashMap<String, Object>();
    map.put("expression", "eq");
    map.put("property", "name");
    map.put("value", name);
    exp.add(map);
    List<User> users = userDao.getByCriteria(exp);
    if (!users.isEmpty()) {
        response.setResponse(users.get(0));
    } else {
        response.setResponse(null);
    }
    return response;
}   

UserDao.java

public List<User> getByCriteria(List<Map<String, Object>> exp) {
  DetachedCriteria criteria = DetachedCriteria.forClass(User.class);
  for (Integer i=0;i<exp.size();i++){
    String expression = (String) exp.get(i).get("expression");
    String property = (String) exp.get(i).get("property");
    if(expression.equals("eq"){
       criteria.add(Restrictions.eq(property,exp.get(i).get("value")));
    }
  }
  return hibernateTemplate.findByCriteria(criteria);
 }

UserTransactionTest.java

private UserTransaction userTransactions = new UserTransaction();
private UserDao userDao = mock(UserDao.class);

@Test
public void testGet() {
   User user = new User();
   user.setName("Raman");
    try {
        when(userDao.getByCriteria(anyList())).thenReturn(user);
    } catch (Exception e) {
        e.printStackTrace();
    }
    ServiceResponse<User> response = userTransactions.get("raman");
    User result = response.getResponse();
    assertEquals("Raman", result.getName());
    assertEquals(0, response.getErrors().size());
}

works fine.

But instead of "anyList()" I passed a user-defined list "myList"

List<Map<String,Object>> myList = new ArrayList<Map<String,Object>>();
Map<String,Object> map = new HashMap<String,Object>();
map.put("expression","eq");
map.put("property","name");
map.put("value","raman");
myList.add(map);
when(userTransactions.getByCriteria(myList)).thenReturn(user);

Throws NullPointerException at the line assertEquals(). Why? What actually happens if anyList() is given?

4 Answers
Related