I am getting a NullPointer exception and while debugging the code I get an InvocationTargetException. I have no clue where am I going wrong. Can someone please help me fix this!!
@Inject
private Log log;
@PersistenceContext(name = Configuration.PERSISTENT_CONTEXT)
private EntityManager em;
public List<Vehicle> getData() {
List<Vehicle> resultList = new ArrayList<>();
try {
String sql = "SELECT v FROM Vehicle v JOIN v.car c WHERE c.carType = 'BMW'";
//getting an InvocationTargetException here while debugging as junit
Query query = em.createQuery(sql, Vehicle.class);
resultList = query.getResultList();
if(resultList == null){
log.error("List is empty or null");
return null;
}
} catch (IllegalArgumentException ex) {
log.info(ex.getMessage());
log.trace(ex.getCause());
}
return resultList;
}
This is my Junit:
@InjectMocks
private FinderManager classUnderTest;
private Query query;
private EntityManager emMock;
@Before
public void setUp(){
emMock = Mockito.mock(EntityManager.class);
query = Mockito.mock(Query.class);
Mockito.mock(Vehicle.class);
}
@Test
public void testMethod(){
List<Vehicle> resultList = new ArrayList<>();
Mockito.when(emMock.createQuery(Mockito.any(String.class)).thenReturn(query);
Mockito.when(query.getResultList()).thenReturn(resultList);
classUnderTest.getData();
}
Trying to find a solution and fix this since so long!
It could be because of the fact that you are mocking createQuery
method with only String as parameter while actually in your method you are invoking createQuery
method with String as well as class parameter.
Mock the method with correct signatures in the test method.
Secondly there is no assertion statement or verify in your test method, what exactly are you going to test?