ЦЕЛЬ: Создание проекта Spring Boot для использования публичного API для NY Times для отображения главных новостей на данный момент.
Что я сделал: Я использовал REST Api и сохранил свой ответ в jsonObject.Я пробовал пройти два юнит-теста, но не смог пройти первый джунтовый тест.Я уверен, что то, что я делаю, неверно, даже несмотря на то, что я прохожу второй тест джунта.
Новости POJO
public class News {
private String title;
private String section;
// GETTER & SETTER
}
Класс службы новостей
@Service public class NewsService {
private String apiKey = "gIIWu7P82GBslJAd0MUSbKMrOaqHjWOo";
public News getTopStories() throws Exception {
RestTemplate restTemplate = new RestTemplate();
News news = new News();
String getUrl = "https://api.nytimes.com/svc/topstories/v2/science.json?api-key=" + apiKey;
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<String>(headers);
ResponseEntity<Map> newsList = restTemplate.exchange(getUrl, HttpMethod.GET, entity, Map.class);
JSONObject jsonObject;
if (newsList.getStatusCode() == HttpStatus.OK) {
jsonObject = new JSONObject(newsList.getBody());
JSONArray jsonArray = jsonObject.getJSONArray("results");
for(int i=0; i<jsonArray.length(); i++) {
news.setTitle(jsonArray.getJSONObject(i).get("title").toString());
news.setSection(jsonArray.getJSONObject(i).get("section").toString());
}
}
// this is only returning the last index of the jsonArray (pretty sure I am suppose to return all to in my URL). Can't seem to come up with the logic to do that.
return news;
}
}
Класс контроллера новостей
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api")
public class NewsController {
@Autowired
NewsService newsService;
@RequestMapping(value = "/news/topstories", method = RequestMethod.GET)
public News getNews() throws Exception {
return newsService.getTopStories();
}
}
Требуется пройти тест JUnit
@Test
public void retrievetest_ok() throws Exception {
mockMvc.perform(get("/api/news/topstories" )).andDo(print())
.andExpect(status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.results.[0].title").exists())
.andExpect(MockMvcResultMatchers.jsonPath("$.section").exists());
}
@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());
}
}
Ошибка, которую я получаю для первого теста JUnit
MockHttpServletRequest:
HTTP Method = GET
Request URI = /api/news/topstories
Parameters = {}
Headers = {}
Handler:
Type = com.example.project.NewsController
Method = public com.example.project.News com.example.project.NewsController.getNews() throws java.lang.Exception
Async:
Async started = false
Async result = null
Resolved Exception:
Type = null
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 200
Error message = null
Headers = {Content-Type=[application/json;charset=UTF-8]}
Content type = application/json;charset=UTF-8
Body = {"title":"Shrinking and Quaking Hint at Moon’s Tectonic Life","section":"Science"}
Forwarded URL = null
Redirected URL = null
Cookies = []
java.lang.AssertionError: No value at JSON path "$.results.[0].title", exception: Missing property in path $['results']
...
...
...
...