JSONObject 期望在路径 $ 中找到属性为 ['XXX'] 的对象

Leo*_*ero 2 java spring-mvc mockmvc

我制作了一个使用第三方 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;
    }
}`
Run Code Online (Sandbox Code Playgroud)

我有我的控制器

@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();
        }
}`
Run Code Online (Sandbox Code Playgroud)

一切正常,但是当我运行测试时(我无法通过内部审计控制更改它)这是我的测试。

@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());
}`
Run Code Online (Sandbox Code Playgroud)

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

2018-07-18 09:40:49.100 INFO 23324 --- [main] osbtmwSpringBootMockServletContext : 初始化 Spring FrameworkServlet '' 2018-07-18 09:40:49.100 INFO 23324 .patTest Servlet
主框架[ servlet] '':初始化开始 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。

Ali*_*ien 5

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

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

.andExpect(jsonPath("[0].title").value("titlevalue0"))
.andExpect(jsonPath("[1].title").value("titlevalue1"))
Run Code Online (Sandbox Code Playgroud)