首页 > 解决方案 > JSONObject 期望在路径 $ 中找到具有属性 ['XXX'] 的对象

问题描述

我制作了一个使用第三方 API 的程序:我有一个名为:NewsService 的服务

@Service
public class NewsService {
    @Autowired
    private NewsRepository newsRepository;
    public List<News> getTopStories() throws Exception{
        RestTemplate restTemplate = new RestTemplate();
        JSONObject news = new JSONObject();
        NewsStories newsentity = new NewsStories();
        List<News> stories = new ArrayList<News>();
        ObjectMapper mapper = new ObjectMapper();
        String getUrl = "https://api.nytimes.com/svc/topstories/v2/home.json?api-key=84e19f8ee1c7489a97481d2ed85af15c";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Map> entity = new HttpEntity<Map>(headers);
        ResponseEntity<Map> newsList = restTemplate.exchange(getUrl, HttpMethod.GET, entity, Map.class);
        if (newsList.getStatusCode() == HttpStatus.OK) {
            news = new JSONObject(newsList.getBody());
            newsentity = mapper.readValue(news.toString(),NewsStories.class);
            newsentity.getStories().forEach(stories::add);
        }
        return stories;
    }
}`

我有我的控制器

@RestController
@RequestMapping("/api/")
public class NewsController {
        @Autowired
        NewsService newsService = new NewsService();
        @RequestMapping(value = "/news/topstories", method = RequestMethod.GET)
        public @ResponseBody List<News> getNews() throws Exception {
            return this.newsService.getTopStories();
        }
}`

一切都很好,但是当我运行我的测试时(我不能通过内部审计控制来改变它)这里是我的测试。

@SpringBootTest
@RunWith(SpringRunner.class)
public class ProjectApplicationTests {
    private MockMvc mockMvc;
    @Autowired
    WebApplicationContext context;
    @Before
    public void setup() {
        mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
    }
    @Test
    public void Newstest_ok() throws Exception {
        mockMvc.perform(get("/api/news/topstories" )).andDo(print())
                .andExpect(status().isOk())
                .andExpect(MockMvcResultMatchers.jsonPath("$.title").exists())
                .andExpect(MockMvcResultMatchers.jsonPath("$.section").exists());
}`

接下来要运行程序,我的程序中的检查验证 Exist() 有问题。你可以帮帮我吗?在运行测试后的日志下方。

2018-07-18 09:40:49.100 INFO 23324 --- [main] osbtmwSpringBootMockServletContext:初始化 Spring FrameworkServlet '' 2018-07-18 09:40:49.100 INFO 23324 --- [
main] ostweb.servlet.TestDispatcherServlet:FrameworkServlet '':初始化开始于 2018-07-18 09:40:49.116 INFO 23324 --- [
IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47) 在 com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242) 在 com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter. java:70) 原因:com.jayway.jsonpath.PathNotFoundException:应在路径 $ 中找到具有属性 ['title'] 的对象,但找到了 'net.minidev.json.JSONArray'。根据 JsonProvider:'com.jayway.jsonpath.spi.json.JsonSmartJsonProvider',这不是一个 json 对象。在 com.jayway.jsonpath.internal.path.PropertyPathToken.evaluate(PropertyPathToken.java:71) 在 com.jayway.jsonpath.internal.path.RootPathToken.evaluate(RootPathToken.java:62) 在 com.jayway.jsonpath.internal .path.CompiledPath.evaluate(CompiledPath.java:53) 在 com.jayway.jsonpath.internal。

`

使用 Postman http://localhost:8080/api/news/topstories我得到 Json 数据,状态为 200 Ok。

标签: javaspring-mvcmockmvc

解决方案


根据 JSON 响应,我们可以看到控制器将主体作为对象数组返回。

要访问 Spring MVC 测试中的每个对象,请使用以下断言:

.andExpect(jsonPath("[0].title").value("titlevalue0"))
.andExpect(jsonPath("[1].title").value("titlevalue1"))

推荐阅读