Mockito- thenReturn(true)仍然在模拟对象上返回false

时间:2017-11-17 08:31:31

标签: unit-testing testing mockito

我最近开始阅读关于Mockito的文章。根据我的理解,以下代码行必须返回true,但它返回false。

测试类

public class PersonServiceImplTest {

   Car car;

   @InjectMocks 
   CarServiceImpl carService;

   @Mock    
   CarDAOImpl carDAO;

   @Before
   public void setUp() {
     MockitoAnnotations.initMocks(this);
   }


   @Test
   public void testUpdateCar() {
     int carId = 1;
     Mockito.when(carDAO.getCarById(any(Integer.class))).thenReturn(new Car());
     carService.updateCar(carId);
Mockito.when(carDAO.isLicenseExpired(any(Car.class))).thenReturn(true);
     Mockito.verify(carDAO).updateCar(any(Car.class));
     Mockito.verify(carDAO, times(1)).isLicenseExpired(any(Car.class));
     Mockito.verify(carDAO, times(1)).issueLicense(any(Car.class));
   }
}

待测试的课程

public class CarServiceImpl implements CarService {

@Autowired carDAO carDAO;

@Override
public Response updateCar(int carId) {

    Car car =carDAO.getCarById(carId);

    try {

        carDAO.updateCar(car);

        if(carDAO.isLicenseExpired(car)))
            carDAO.issueLicense(car);

    } catch (Exception e) {

        log.error(e.getMessage());

        return Response.status(Status.INTERNAL_SERVER_ERROR).build();

    }

    return Response.ok(Status.CREATED).build();
}

如果需要,CarDAOImpl处理数据库也会更新。

提前致谢。

1 个答案:

答案 0 :(得分:1)

这两行的排序不正确:

carService.updateCar(carId); 
Mockito.when(carDAO.isLicenseExpired(Mockito.any(Car.class))).thenReturn(true);

该对中的第一行调用被测试类,第二行设置对carDAO在被测试类中的行为的期望。因此,您在调用之后设置了期望

以下测试将通过:

@Test
public void testUpdateCar() {
    int carId = 1;

    // establish expectations of how carDAO should behave inside updateCar()
    Mockito.when(carDAO.getCarById(Mockito.any(Integer.class))).thenReturn(new Car());
    Mockito.when(carDAO.isLicenseExpired(Mockito.any(Car.class))).thenReturn(true);

    // invoke the class-under-test
    carService.updateCar(carId);

    // verify that CarService used CarDAO correctly
    Mockito.verify(carDAO).updateCar(Mockito.any(Car.class));
    Mockito.verify(carDAO).isLicenseExpired(Mockito.any(Car.class));
    Mockito.verify(carDAO).issueLicense(Mockito.any(Car.class));
}