[英]Mockito - mock object inside method
I have a method that return the list of vehicles. 我有一个返回车辆清单的方法。 Like this: 像这样:
public List<Vehicle> getVehicles() {
List<Vehicle> vehicles=vehicleDAO.getAllVehicles();
for (Vehicle v : vehicles){//NullPointerException
//some bussines logic...
}
return vehicles;
}
And here is my test: 这是我的测试:
@Test
public void testShowVehicles() {
when(vehicleDAO.getAllVehicles()).thenReturn(listVehiclesMock);
List<Vehicle> vehicles= service.getVehicles();//NullPointerException
assertEquals(listVehicleMock, vehicles);
}
When I run it I get NullPointerException because Vehicle does not exists. 当我运行它时,我得到NullPointerException,因为Vehicle不存在。 When I have old fashion for loop it passes the test, but now I replaced with forEach loop I get error in test. 当我有旧时尚for循环它通过测试,但现在我用forEach循环替换我在测试中得到错误。 So how would I mock the object Vehicle? 那么我该如何模拟对象车辆呢?
For each loop uses iterator()
method of the given Iterable
. 对于每个循环使用给定Iterable
iterator()
方法。 An iterator obtained that way is then used to iterate over the collection. 然后使用以这种方式获得的迭代器来迭代集合。 Unfortunately, this method of the mocked list returns null, which causes NullPointerException
. 不幸的是,这个模拟列表的方法返回null,这会导致NullPointerException
。 To use for each loop syntax you have to bind iterator()
method to result as well. 要用于每个循环语法,您还必须将iterator()
方法绑定到结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.