java - Junit 测试中的模拟错误 UnfinishedStubbingException

标签 java json junit mockito

我创建了一个测试来尝试我的微服务。一个简单的 get 调用通过 3 个参数向我返回包含该用户规范的消息。我使用 Junit 和 Mockito 创建了它。如下:

@Test
public void TestOk() throws Exception{
    CarsRequest carsRequest = new CarsRequest();
    carsRequest.setName(TestCostants.NAME);
    carsRequest.setPlate(TestCostants.PLATE);
    carsRequest.setPrice(TestCostants.PRICE);
    Cars car = new Cars("BMW","TG35647", "15000","re",80000000,
            null,null);
    List<Cars> cars = new ArrayList<>();
    cars.add(car);


    Mockito.when(
            service.getByPlate(carsRequest.getName(), carsRequest.getPlate(),
                    carsRequest.getPrice())).thenReturn(cars);
    RequestBuilder requestBuilder = MockMvcRequestBuilders.get(
            "/resources/cars").accept(
            MediaType.APPLICATION_JSON).header("Authorization","Basic //myAuth");
    MvcResult result = mockMvc.perform(requestBuilder).andReturn();
    System.out.println(result.getResponse());


    String expected = "{\"name\"=\"BMW\", \"plate\"=\"TG35647\", " +
            "\"price\"=\"15000\",\"brand\"=\"re\", \"kilometers\"=\"80000000\", \"revisiondate\"=\"null\", \"owner\"=\"null\"}";
    JSONAssert.assertEquals(expected, result.getResponse()
            .getContentAsString(), false);
});

显然,传递的变量常量与必须返回给我的消息的常量一致。当我尝试开始测试时出现错误 这是我报告的堆栈跟踪:

2021-03-29 12:45:07.906 [main] INFO  o.s.s.l.SpringSecurityLdapTemplate - Ignoring PartialResultException
{
  "@timestamp" : "2021-03-29T12:45:08.119+02:00",
  "@version" : "1",
  "message" : "[GET] http://localhost/resources/cars/ call resulted in the following error: Content type '' not supported",
  "logger_name" : "my.project.car.controller.ExceptionHandlingController",
  "thread_name" : "main",
  "level" : "ERROR",
  "level_value" : 40000
}
ErrorResponse: org.springframework.web.HttpMediaTypeNotSupportedException: Content type '' not supported
org.springframework.mock.web.MockHttpServletResponse@135f160e
MockHttpServletRequest:
      HTTP Method = GET
      Request URI = /resources/cars/
       Parameters = {}
          Headers = [Accept:"application/json", Authorization:"Basic //myAuth"]
             Body = null
    Session Attrs = {}
Handler:
             Type = null
Async:
    Async started = false
     Async result = null
Resolved Exception:
             Type = org.springframework.web.HttpMediaTypeNotSupportedException
ModelAndView:
        View name = null
             View = null
            Model = null
FlashMap:
       Attributes = null
MockHttpServletResponse:
           Status = 500
    Error message = null
          Headers = [Content-Type:"application/json", X-Content-Type-Options:"nosniff", X-XSS-Protection:"1; mode=block", Cache-Control:"no-cache, no-store, max-age=0, must-revalidate", Pragma:"no-cache", Expires:"0", X-Frame-Options:"DENY"]
     Content type = application/json
             Body = {"esito":"KO","codiceEsito":"ERROR","descrizioneEsito":"Errore generico"}
    Forwarded URL = null
   Redirected URL = null
          Cookies = []
java.lang.AssertionError:
Expected: name
     but none found
 ;
Expected: plate
     but none found
 ;
Expected: price
     but none found
 ;
Expected: brand
     but none found
 ;
Expected: kilometers
     but none found
 ;
Expected: revisiondate
     but none found
 ;
Expected: owner
     but none found
 ;

尝试进入“调试”,我收到此错误,但我根本不知道如何处理它

Method threw 'org.mockito.exceptions.misusing.UnfinishedStubbingException' exception. Cannot evaluate my.project.service.CarService$MockitoMock$1824138024.toString()

我猜这两个错误是相关的,但我不知道如何解决这个问题。

编辑: 根据要求,我添加了我的汽车服务:

@Service
public class CarService {
    @Autowired
    CarRepository carRepository;
    @Autowired
    ObjectMapper objectMapper;

    public List<Car> getByPlate(String name, String plate, String price) throws JsonProcessingException {
        List<Car> car = new ArrayList<>();
        for (Cache.Entry<String, Car> entry: carRepository.findAllByNameAndPlateAndPrice(name, plate,price)){
            car.add(new Car(entry.getKey(), entry.getValue()));
            System.out.println("Entry: " + objectMapper.writeValueAsString(entry));
        }
        return cars;
    }
}

和我的 CarController

@RestController
@RequestMapping("/resources/")
public class CarController {
    @Autowired
    CarService carService;
    @Autowired
    ObjectMapper objectMapper;
    @GetMapping(
    value = "/cars",
    consumes = {MediaType.APPLICATION_JSON_VALUE},
    produces = {MediaType.APPLICATION_JSON_VALUE})
    public CarsResponse getCars(@RequestBody CarsRequest request) throws IOException {
        //some code
    }

最佳答案

首先,使用带有正文的 GET 请求是 poor practice 。请改用 POST 请求。

然后,spring 会告诉您有关 org.springframework.web.HttpMediaTypeNotSupportedException 的信息,并在您的 Controller 方法 getCars() 中描述下一个:

    consumes = {MediaType.APPLICATION_JSON_VALUE},
    produces = {MediaType.APPLICATION_JSON_VALUE}

但是在您的测试中您没有指定任何内容类型:

RequestBuilder requestBuilder = MockMvcRequestBuilders.get(
        "/resources/cars").accept(
        MediaType.APPLICATION_JSON).header("Authorization","Basic //myAuth");

尝试添加内容类型.contentType(MediaType.APPLICATION_JSON):

 RequestBuilder requestBuilder = MockMvcRequestBuilders.get("/resources/cars")
                .accept(MediaType.APPLICATION_JSON)
                .contentType(MediaType.APPLICATION_JSON)
                .header("Authorization", "Basic //myAuth");

另外,我不明白你如何将正文传递给请求。尝试添加它 .content(mapper.writeValueAsString(carsRequest)):

 RequestBuilder requestBuilder = MockMvcRequestBuilders.get("/resources/cars")
                .accept(MediaType.APPLICATION_JSON)
                .contentType(MediaType.APPLICATION_JSON)
                .header("Authorization", "Basic //myAuth")
                .content(mapper.writeValueAsString(carsRequest));

其中mapperObjectMapper。我假设您正在使用com.fasterxml.jackson.databind.ObjectMapper

关于java - Junit 测试中的模拟错误 UnfinishedStubbingException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66853989/

相关文章:

java - Aspect 中的 session 作用域 bean

javascript - 如何解析 json 并根据值在 HTML 表中显示不同的颜色?

javascript - 使用javascript解析json数组

java - Spring MVC 的 junit 测试用例

java - 无法从静态内容引用非静态变量 jTextArea

java - 在 Java 中(在 Intel CPU 上)对许多短字符串值进行 SHA-256 编码的最快方法是什么?

java - 从数组中挑选值(value)最高和值(value)最低的一天时遇到麻烦

javascript - (Angular) 插入一个对象到 json 数组

java - 如何使用JUNIT测试ENUM

java - TDD,不可能有异常(exception)