为什么是Mockito.when(..).doReturn(..) 如果从 Mockito.doAnswer(..) 调



我需要测试一个创建Car对象并使用CarDao将其保存在数据库中的方法。另一个方法Car对象创建,但如果CarDao是模拟的,则car.getUser()返回null而不是正确的User对象。这是我的代码。

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());

为什么carDao.getById(carId).getUser()返回空值?我需要做什么才能获得具有正确user字段值的完整对象?

更新

carDao用法:

Car car = carService.create("car name1", "color", "year", user); // in this method called carDao.persist(...);
car.setColor("color2");
carService.findById(car.getId());
// this method calls carDao.getById(carId) 
// and comapres with authenticated user ID. 
// But carDao.getById(carId) returns car with user == null

下面是CarService类的一部分,其中代码抛出 NullPointerException。

// carService.findById(...) method
public Car findById(Car id) {
    Car car = carDao.getById(id);
    User carUser = car.getUser(); // returns null
    User currentUser = accountService.getAuthenticatedUser(); // returns correct user object
    if (!carUser.getId().equals(currentUser.getId())) { // throws NullPointerException
        return null;
    }
    return car;
}

谢谢。

据我了解,您有一些想要测试的类,让我们将其称为Handler。在此处理程序中,您可以使用CarService在数据库中"构建和存储"汽车对象,并在数据库中"查找"汽车对象(并进行一些User验证)。在CarService中,您可以使用CarDao来处理DB。
所以首先:如果你测试 Handler 类,那么你需要模拟它自己的依赖,这意味着你需要模拟 CarService,而不是 CarService 内部的 CarDao(不是嵌套依赖的第二级)。每当你测试CarService时,你需要嘲笑CadDao,它应该与CarHandlerTest分开测试。

第二:我模拟了你的例子,它有效,请参阅下面的代码。

public class User {} //simple user just to verify not null
public class Car {
    private Long id;
    private User user;
    //getters ans setters
}
public class CarDao { //with stub methods because we will mock it
    public void persist(Car car) {}
    public Car getById(Long id) {return new Car();}
}
public class CarHandler {
    private CarService carService; //with setter
    public void foo() { // we will test this method
        User user = new User(); //it's like your example but without additional fields (like color)
        Car car = carService.create(user); // here we build and store new car
        Car sameCar = carService.findById(car.getId());
        assert car == sameCar;
    }
}
public class CarService {
    private CarDao carDao; //with setter
    public Car create(User user) {
        Car car = new Car();
        car.setUser(user);
        carDao.persist(car); //here car should get id
        return car;
    }
    public Car findById(Long id) {
        Car car = carDao.getById(id);
        User user = car.getUser(); //this user should be not null in test
        assert user != null; //this assert for verify user
        return car;
    }
}

最有趣的部分 - 测试。

public class CarHandlerTest {
    static long lastCarId = 5;
    private CarHandler carHandler = new CarHandler();
    private CarService carService = new CarService();
    private CarDao carDao;
    @Test
    public void testFoo() throws Exception {
        carDao = Mockito.mock(CarDao.class);
        carService.setCarDao(carDao);
        carHandler.setCarService(carService);
        Mockito.doAnswer(new Answer<Void>() { //I copy it from your example
            @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());
        carHandler.foo();
    }
}

您还可以从该方法返回foo() Car并验证测试中的所有内容。

相关内容

  • 没有找到相关文章

最新更新