【发布时间】:2021-03-20 19:55:11
【问题描述】:
我正在为我的 Springboot 应用程序创建测试。应用程序通过 Get 调用,在 RequestBody 中传递我的“CarRequest”
public class CarsRequest implements Serializable {
private String name;
private String plate ;
private String price;
}
它将与该数据相关的汽车规格返回给我
{
"name":"",
"plate":"",
"price":"",
"brand":"",
"kilometers":"",
"revisiondate":"",
"owner":""
}
我使用 Mockito 做了这个简单的测试,但我不明白为什么我的服务默认设置为 null,这会将所有内容都抛出 NullPointErexception
public class CarTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private CarService service;
@Autowired
ObjectMapper objectMapper;
@Test
public void TestOk() throws Exception{
CarsRequest carsRequest = new CarsRequest();
Car car = new Car();
List<Car> cars = new ArrayList<>();
//septum the fields of cars and add them to the list
cars.add(car);
Mockito.when(
service.getByPlate("bmw",
"TG23IO", "1500")).thenReturn(cars);
RequestBuilder requestBuilder = MockMvcRequestBuilders.get(
"/garage/cars").accept(
MediaType.APPLICATION_JSON);
MvcResult result = mockMvc.perform(requestBuilder).andReturn();
System.out.println(result.getResponse());
String expected = "{name:"bmw","plate":"TG23IO","price":"1500","brand":"POL","kilometers":"80000","revisiondate":"2016-03-15","owner":"JohnLocke"}";
JSONAssert.assertEquals(expected, result.getResponse()
.getContentAsString(), false);
}
}
下面我还添加了我的 CarService
@Service
public class CarService {
@Autowired
CarRepository carRepository;
@Autowired
ObjectMapper objectMapper;
public List<Cars> getByContratto(String name, String plate, String price) throws JsonProcessingException {
//some code, extraction logic
return cars;
}
}
应用程序运行良好,只有测试不起作用。作为测试写作的新手,我无法弄清楚我的 Carservice 上的 null 是什么原因造成的。 如果需要,我也可以包含 Controller Get 和存储库,但我认为它们无济于事
【问题讨论】: