jeudi 28 avril 2016

Why Mockito.when(...).doReturn(...) not working as expected if it called from Mockito.doAnswer(...)

I need to test a method which creates Car object and uses CarDao to save it in database. Another method gets created Car object but if CarDao is mock then car.getUser() returns null instead of correct User object. This is my code.

Mockito.doAnswer(new Answer<Void>() {
        @Override
        public Void answer(InvocationOnMock invocationOnMock) throws Throwable {
            lastCarId++;
            Car car = (Car) invocationOnMock.getArguments()[0];
            // here car.getUser() returns correct user object
            car.setId(lastCarId);
            Mockito.when(carDao.getById(car.getId())).thenReturn(car);
            return null;
        }
    }).when(carDao).persist(Mockito.any());

Why carDao.getById(carId).getUser() returns null? And what I need to do to get full object with correct user field value?

Thanks.

Aucun commentaire:

Enregistrer un commentaire