java.lang.Ошибка утверждения: Нет значения в пути JSON «имя»

#spring #testing

Вопрос:

java.lang.Ошибка утверждения: Нет значения в пути JSON «имя» в org.springframework.test.util.JsonPathExpectationsHelper.EvaluateJsonPath(JsonPathExpectationsHelper.java:304) в org.springframework.test.util.Значение JsonPathExpectationsHelper.assert(JsonPathExpectationsHelper.java:99) в org.springframework.test.web.servlet.результат.JsonPathResultMatchers.лямбда$значение$2(JsonPathResultMatchers.java:111) в org.springframework.test.web.сервлет.MockMvc$1.И ожидайте(MockMvc.java:212) в com.nix.tdd.CarControllerTest.getCar_ShouldRetuenCar(CarControllerTest.java:29) в sun.reflect.NativeMethodAccessorImpl.invoke0(Собственный метод) в sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) в sun.reflect.Делегирование methodaccessorimpl.invoke(делегирование methodaccessorimpl.java:43) в java.lang.reflect.Метод.вызов(Метод.java:498) в org.junit.runners.model.Метод работы с кадрами$1.runReflectiveCall(метод работы с кадрами.java:59) в org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) в org.junit.runners.model.FrameworkMethod.Вызывайте эксплозивно(FrameworkMethod.java:56) в организации.junit.внутренние.бегуны.заявления.Вызов метода.оценка(вызов метода.java:17) в org.springframework.тест.контекст.junit4.инструкции.RunBeforeTestExecutionCallbacks.оценить(RunBeforeTestExecutionCallbacks.java:74) в org.springframework.тест.контекст.junit4.инструкции.RunAfterTestExecutionCallbacks.оценить(RunAfterTestExecutionCallbacks.java:84) в org.springframework.тест.контекст.junit4.инструкции.RunBeforeTestMethodCallbacks.оценка(RunBeforeTestMethodCallbacks.java:75) в организации.springframework.тест.контекст.junit4.инструкции.Запустите тестовый метод обратных вызовов. оцените(RunAfterTestMethodCallbacks.java:86) в org.springframework.test.context.junit4.инструкции.SpringRepeat.оценка(SpringRepeat.java:84) в org.junit.runners.ParentRunner.Лист запуска(ParentRunner.java:366) в org.springframework.тест.контекст.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251) в org.springframework.тест.контекст.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97) в org.junit.runners.ParentRunner$4.запустите(ParentRunner.java:331) в организации.джунит,бегуны.ParentRunner$1.расписание(ParentRunner.java:79) в org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329) в org.junit.runners.ParentRunner.доступ к 100 долларам(ParentRunner.java:66) в org.junit.runners.ParentRunner$2.оцените(ParentRunner.java:293) в org.springframework.тест.контекст.junit4.инструкции.RunBeforeTestClassCallbacks.оценить(RunBeforeTestClassCallbacks.java:61) в org.springframework.тест.контекст.junit4.инструкции.RunAfterTestClassCallbacks.оцените(RunAfterTestClassCallbacks.java:70) в org.junit.runners.ПарентРаннер$3.оцените(ПарентРаннер.java:306) в org.junit.runners.ParentRunner.run(ParentRunner.java:413)

Ниже приведен полный набор кода.

 package com.nix.tdd;   import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;  import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;   import org.springframework.boot.test.web.client.TestRestTemplate;   import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc;   @RunWith(SpringRunner.class) @WebMvcTest(CarController.class) public class CarControllerTest {    @Autowired  private MockMvc mockMvc;    @Test  public void getCar_ShouldRetuenCar() throws Exception{   this.mockMvc.perform(get("/cars/dezire"))  .andExpect(status().isOk())  .andExpect(jsonPath("name").value("dezire"))  .andExpect(jsonPath("type").value("diesel"));  }  }  

 package com.nix.tdd;  import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;  @SpringBootApplication public class TddApplication {   public static void main(String[] args) {  SpringApplication.run(TddApplication.class, args);  }  }  

 package com.nix.tdd;  import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController;  import com.nix.tdd.domain.Car;  @RestController public class CarController {   @GetMapping("/cars/{name}")  private Car getCar(@PathVariable String name) {  return null;  } }  

pom.xml

 lt;?xml version="1.0" encoding="UTF-8"?gt; lt;project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"gt;  lt;modelVersiongt;4.0.0lt;/modelVersiongt;  lt;parentgt;  lt;groupIdgt;org.springframework.bootlt;/groupIdgt;  lt;artifactIdgt;spring-boot-starter-parentlt;/artifactIdgt;  lt;versiongt;2.6.0lt;/versiongt;  lt;relativePath/gt; lt;!-- lookup parent from repository --gt;  lt;/parentgt;  lt;groupIdgt;com.nix.tddlt;/groupIdgt;  lt;artifactIdgt;TDDlt;/artifactIdgt;  lt;versiongt;0.0.1-SNAPSHOTlt;/versiongt;  lt;namegt;TDDlt;/namegt;  lt;descriptiongt;LoginJJWTlt;/descriptiongt;  lt;propertiesgt;  lt;java.versiongt;1.8lt;/java.versiongt;  lt;/propertiesgt;  lt;dependenciesgt;  lt;dependencygt;  lt;groupIdgt;org.springframework.bootlt;/groupIdgt;  lt;artifactIdgt;spring-boot-starter-weblt;/artifactIdgt;  lt;/dependencygt;   lt;dependencygt;  lt;groupIdgt;org.springframework.bootlt;/groupIdgt;  lt;artifactIdgt;spring-boot-starter-testlt;/artifactIdgt;  lt;scopegt;testlt;/scopegt;  lt;/dependencygt;  lt;/dependenciesgt;   lt;buildgt;  lt;pluginsgt;  lt;plugingt;  lt;groupIdgt;org.springframework.bootlt;/groupIdgt;  lt;artifactIdgt;spring-boot-maven-pluginlt;/artifactIdgt;  lt;/plugingt;  lt;/pluginsgt;  lt;/buildgt;  lt;/projectgt;  

Комментарии:

1. Вы возвращаетесь null из Controller и утверждаете значение (в частности, по пути json $.name ). Там нет никакой ценности, потому что вы вернулись null .

2. Спасибо , что ж, вы правы. Это работает после возврата объекта автомобиля. @GetMapping(«/автомобили/{имя}») личный автомобиль getCar(@Имя переменной строки пути) { Автомобиль = новый автомобиль(«дизель»,» дизель»); возвращаемый автомобиль; }