瀏覽代碼

increased test coverage for news

Ahmad Rusdi 6 年之前
父節點
當前提交
6b69a3047d

+ 0
- 7
server/pom.xml 查看文件

@@ -51,13 +51,6 @@
51 51
 			<groupId>com.fasterxml.jackson.core</groupId>
52 52
 			<artifactId>jackson-databind</artifactId>
53 53
 		</dependency>
54
-
55
-		<dependency>
56
-			<groupId>org.json</groupId>
57
-			<artifactId>json</artifactId>
58
-			<version>20180130</version>
59
-		</dependency>
60
-
61 54
 	</dependencies>
62 55
 
63 56
 	<build>

+ 9
- 0
server/src/main/java/com/stockr/server/exception/MissingQueryParameters.java 查看文件

@@ -0,0 +1,9 @@
1
+package com.stockr.server.exception;
2
+
3
+import org.springframework.http.HttpStatus;
4
+import org.springframework.web.bind.annotation.ResponseStatus;
5
+
6
+@ResponseStatus(value = HttpStatus.BAD_REQUEST)
7
+public class MissingQueryParameters extends RuntimeException{
8
+
9
+}

+ 6
- 6
server/src/main/java/com/stockr/server/news/NewsController.java 查看文件

@@ -1,19 +1,19 @@
1 1
 package com.stockr.server.news;
2 2
 
3
+import com.stockr.server.exception.MissingQueryParameters;
3 4
 import org.springframework.beans.factory.annotation.Autowired;
4
-import org.springframework.web.bind.annotation.GetMapping;
5
-import org.springframework.web.bind.annotation.RestController;
5
+import org.springframework.web.bind.annotation.*;
6 6
 
7 7
 import java.util.ArrayList;
8
-import java.util.List;
9 8
 
10 9
 @RestController
10
+@RequestMapping("news")
11 11
 public class NewsController {
12 12
     @Autowired
13 13
     NewsService ns;
14 14
 
15
-    @GetMapping("/news")
16
-    public ArrayList<Article> getAllArticles() {
17
-        return ns.getAllArticles();
15
+    @GetMapping// root
16
+    public ArrayList<Article> getAllArticles(@RequestParam("query") String query) throws MissingQueryParameters{
17
+        return ns.getAllArticles(query);
18 18
     }
19 19
 }

+ 32
- 10
server/src/main/java/com/stockr/server/news/NewsService.java 查看文件

@@ -1,6 +1,10 @@
1 1
 package com.stockr.server.news;
2 2
 
3 3
 import org.springframework.boot.web.client.RestTemplateBuilder;
4
+import org.springframework.http.HttpEntity;
5
+import org.springframework.http.HttpHeaders;
6
+import org.springframework.http.HttpMethod;
7
+import org.springframework.http.ResponseEntity;
4 8
 import org.springframework.stereotype.Service;
5 9
 import org.springframework.web.client.RestTemplate;
6 10
 
@@ -8,24 +12,42 @@ import java.util.ArrayList;
8 12
 
9 13
 @Service
10 14
 public class NewsService {
11
-    private final String url = "https://newsapi.org/v2/everything?q=facebook" +
12
-            "&language=en" +
13
-            "&sources=bloomberg,business-insider,cnbc,the-wall-street-journal" +
14
-            "&pageSize=100" +
15
-            "&apiKey=";
16
-    // TODO - http header "X-Api-Key": "key"
15
+    // TODO - hide key(?)
17 16
     private final String key = "471b872d96ca40c4a1d0f21de4bb061e";
18 17
     private final RestTemplate rt;
18
+    private HttpEntity entity;
19 19
 
20 20
     public NewsService(RestTemplateBuilder rtb) {
21
+        initHeaders();
21 22
         rt = rtb.build();
22 23
     }
23 24
 
24
-    public News getNews() {
25
-        return rt.getForObject(url + key, News.class);
25
+    private void initHeaders() {
26
+        HttpHeaders headers = new HttpHeaders();
27
+        headers.set("X-Api-Key", key);
28
+        entity = new HttpEntity(headers);
26 29
     }
27 30
 
28
-    public ArrayList<Article> getAllArticles() {
29
-        return getNews().getArticles();
31
+    News getNews(String query) {
32
+        ResponseEntity<News> re = rt.exchange(
33
+                insertQueryInUrl(query),
34
+                HttpMethod.GET,
35
+                entity,
36
+                News.class
37
+        );
38
+        News n = re.getBody();
39
+        return n;
40
+    }
41
+
42
+    ArrayList<Article> getAllArticles(String query) {
43
+        return getNews(query)
44
+                .getArticles();
45
+    }
46
+
47
+    String insertQueryInUrl(String query) {
48
+        return  "https://newsapi.org/v2/everything?q=" + query +
49
+                "&language=en" +
50
+                "&sources=bloomberg,business-insider,cnbc,the-wall-street-journal" +
51
+                "&pageSize=100";
30 52
     }
31 53
 }

+ 0
- 1
server/src/test/java/com/stockr/server/news/ArticleTest.java 查看文件

@@ -4,7 +4,6 @@ import com.fasterxml.jackson.databind.ObjectMapper;
4 4
 import org.junit.Test;
5 5
 
6 6
 import java.io.IOException;
7
-import java.util.ArrayList;
8 7
 
9 8
 import static org.junit.Assert.*;
10 9
 

+ 51
- 0
server/src/test/java/com/stockr/server/news/NewsControllerTest.java 查看文件

@@ -0,0 +1,51 @@
1
+package com.stockr.server.news;
2
+
3
+import static org.hamcrest.Matchers.containsString;
4
+import static org.mockito.Mockito.when;
5
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
6
+import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
7
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
8
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.handler;
9
+
10
+import org.junit.Test;
11
+import org.junit.runner.RunWith;
12
+import org.springframework.beans.factory.annotation.Autowired;
13
+import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
14
+import org.springframework.boot.test.mock.mockito.MockBean;
15
+import org.springframework.test.context.junit4.SpringRunner;
16
+import org.springframework.test.web.servlet.MockMvc;
17
+
18
+@RunWith(SpringRunner.class)
19
+@WebMvcTest(NewsController.class)
20
+public class NewsControllerTest {
21
+
22
+    @Autowired
23
+    private MockMvc mockMvc;
24
+
25
+    @MockBean
26
+    private NewsService service;
27
+
28
+    @Test
29
+    public void news_Should_Use_Method_getAllArticles() throws Exception {
30
+        when(service.getNews("test")).thenReturn(new News());
31
+        this.mockMvc.perform(get("/news?query=fb"))
32
+                .andDo(print())
33
+                .andExpect(handler().methodName("getAllArticles"));
34
+    }
35
+
36
+    @Test
37
+    public void news_Should_Return_A_Json_Array() throws Exception {
38
+        when(service.getNews("test")).thenReturn(new News());
39
+        this.mockMvc.perform(get("/news?query=fb"))
40
+                .andDo(print())
41
+                .andExpect(content().string("[]"));
42
+    }
43
+
44
+    @Test
45
+    public void news_When_No_Queries_Throw_Exception() throws Exception {
46
+        when(service.getNews("test")).thenReturn(new News());
47
+        this.mockMvc.perform(get("/news"))
48
+                .andDo(print())
49
+                .andExpect(content().string("[]"));
50
+    }
51
+}

+ 46
- 19
server/src/test/java/com/stockr/server/news/NewsServiceTest.java 查看文件

@@ -2,26 +2,25 @@ package com.stockr.server.news;
2 2
 
3 3
 import com.fasterxml.jackson.core.JsonProcessingException;
4 4
 import com.fasterxml.jackson.databind.ObjectMapper;
5
+import org.hamcrest.Matchers;
6
+import org.junit.Assert;
5 7
 import org.junit.Before;
6 8
 import org.junit.Ignore;
7 9
 import org.junit.Test;
8 10
 import org.junit.runner.RunWith;
9
-import org.mockito.InjectMocks;
10
-import org.mockito.Mock;
11
-import org.mockito.Mockito;
12 11
 import org.springframework.beans.factory.annotation.Autowired;
13 12
 import org.springframework.boot.test.autoconfigure.web.client.RestClientTest;
14 13
 import org.springframework.boot.web.client.RestTemplateBuilder;
14
+import org.springframework.http.HttpMethod;
15 15
 import org.springframework.http.MediaType;
16 16
 import org.springframework.test.context.junit4.SpringRunner;
17 17
 import org.springframework.test.web.client.MockRestServiceServer;
18
-import org.springframework.web.client.RestTemplate;
19 18
 
20
-import javax.print.attribute.standard.Media;
21
-import java.awt.*;
22 19
 import java.util.ArrayList;
23 20
 
24 21
 import static org.junit.Assert.*;
22
+import static org.springframework.test.web.client.match.MockRestRequestMatchers.header;
23
+import static org.springframework.test.web.client.match.MockRestRequestMatchers.method;
25 24
 import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo;
26 25
 import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess;
27 26
 
@@ -37,36 +36,64 @@ public class NewsServiceTest {
37 36
     @Autowired
38 37
     private ObjectMapper om;
39 38
 
39
+    private String JSON;
40
+
40 41
     @Before
41 42
     public void setUp() throws JsonProcessingException {
43
+        setUpJsonResponse();
44
+        setUpMrss();
45
+    }
46
+
47
+    private void setUpMrss() {
48
+        mrss.expect(requestTo(ns.insertQueryInUrl("test")))
49
+                .andExpect(method(HttpMethod.GET))
50
+                .andExpect(header("X-Api-Key", Matchers.containsString("")))
51
+                .andRespond(withSuccess(JSON, MediaType.APPLICATION_JSON));
52
+    }
53
+
54
+    private void setUpJsonResponse() throws JsonProcessingException {
42 55
         ArrayList<Article> al = new ArrayList<>();
43 56
         Article a = new Article();
44 57
         a.setAuthor("Author Name");
45 58
         al.add(a);
46 59
         News n = new News();
47 60
         n.setArticles(al);
61
+        JSON = om.writeValueAsString(n);
62
+    }
48 63
 
49
-        String nstr = om.writeValueAsString(n);
50
-        String url = "https://newsapi.org/v2/everything?q=bitcoin&apiKey=";
51
-        String key = "471b872d96ca40c4a1d0f21de4bb061e";
64
+    @Test
65
+    public void getNews_Should_Hit_The_Proper_Endpoint() {
66
+        ns.getNews("test");
67
+        mrss.verify();
68
+    }
52 69
 
53
-        this.mrss.expect(requestTo(url + key))
54
-                .andRespond(withSuccess(nstr, MediaType.APPLICATION_JSON));
70
+    @Test
71
+    public void getNews_Should_Send_XApiKey_Header() {
72
+        ns.getNews("test");
73
+        mrss.verify();
55 74
     }
75
+
56 76
     @Test
57
-    public void getNewsTest() {
58
-        News ne = this.ns.getNews();
77
+    public void getNews_Should_Parse_The_JSON_Properly() {
78
+        News ne = ns.getNews("test");
59 79
         assertEquals("Author Name", ne.getArticles().get(0).getAuthor());
60 80
     }
61 81
 
62 82
     @Test
63
-    @Ignore
64
-    public void test() {
65
-        RestTemplateBuilder rt = new RestTemplateBuilder();
66
-        NewsService ns = new NewsService(rt);
83
+    public void getAllArticles_Should_Return_An_ArrayList() {
84
+        ArrayList ne = ns.getAllArticles("test");
85
+        assertNotNull(ne);
86
+    }
67 87
 
68
-        ArrayList<Article> ne = ns.getAllArticles();
69
-        System.out.println(ne);
70 88
 
89
+    @Test
90
+    public void insertQueryInUrl_Given_Query_Should_Insert_In_Url() {
91
+        String query = "tesla";
92
+        String expected = "https://newsapi.org/v2/everything?q=" + query +
93
+                "&language=en" +
94
+                "&sources=bloomberg,business-insider,cnbc,the-wall-street-journal" +
95
+                "&pageSize=100";
96
+        String actual = ns.insertQueryInUrl(query);
97
+        assertEquals(expected, actual);
71 98
     }
72 99
 }