浏览代码

updated controller tests to reflect readme

Demetrius Murray 5 年前
父节点
当前提交
f22befbcc0

+ 12
- 0
pom.xml 查看文件

@@ -49,6 +49,18 @@
49 49
 			<artifactId>spring-boot-starter-data-jpa</artifactId>
50 50
 			<!--<version>1.3.5.RELEASE</version>-->
51 51
 		</dependency>
52
+        <dependency>
53
+            <groupId>org.mockito</groupId>
54
+            <artifactId>mockito-core</artifactId>
55
+            <version>1.10.19</version>
56
+            <exclusions>
57
+                <exclusion>
58
+                    <groupId>org.hamcrest</groupId>
59
+                    <artifactId>hamcrest-core</artifactId>
60
+                </exclusion>
61
+            </exclusions>
62
+            <scope>test</scope>
63
+        </dependency>
52 64
 
53 65
     </dependencies>
54 66
 

+ 1
- 1
src/main/java/io/zipcoder/crudapp/controllers/PersonController.java 查看文件

@@ -39,7 +39,7 @@ public class PersonController {
39 39
     }
40 40
 
41 41
     @RequestMapping(value = "/people/{id}", method = RequestMethod.DELETE)
42
-    public ResponseEntity<?> deletePerson(@PathVariable Long id){
42
+    public ResponseEntity<Void> deletePerson(@PathVariable Long id){
43 43
         personService.deletePerson(id);
44 44
         return new ResponseEntity(HttpStatus.NO_CONTENT);
45 45
     }

+ 16
- 1
src/main/java/io/zipcoder/crudapp/models/Person.java 查看文件

@@ -16,7 +16,8 @@ public class Person {
16 16
     @Column(name = "LAST_NAME")
17 17
     String lastName;
18 18
 
19
-    public Person(){}
19
+    public Person() {
20
+    }
20 21
 
21 22
     public Person(String firstName, String lastName) {
22 23
         this.firstName = firstName;
@@ -42,4 +43,18 @@ public class Person {
42 43
     public void setLastName(String lastName) {
43 44
         this.lastName = lastName;
44 45
     }
46
+
47
+    @Override
48
+    public boolean equals(Object o) {
49
+        return toString().equals(o.toString());
50
+    }
51
+
52
+    @Override
53
+    public String toString() {
54
+        return "Person{" +
55
+                "id=" + id +
56
+                ", firstName='" + firstName + '\'' +
57
+                ", lastName='" + lastName + '\'' +
58
+                '}';
59
+    }
45 60
 }

+ 158
- 0
src/test/java/io/zipcoder/crudapp/PersonControllerTestMVC.java 查看文件

@@ -0,0 +1,158 @@
1
+package io.zipcoder.crudapp;
2
+
3
+import com.fasterxml.jackson.databind.ObjectMapper;
4
+import io.zipcoder.crudapp.controllers.PersonController;
5
+import io.zipcoder.crudapp.models.Person;
6
+import io.zipcoder.crudapp.services.PersonService;
7
+import org.apache.catalina.filters.CorsFilter;
8
+import org.junit.Before;
9
+import org.junit.Test;
10
+import org.junit.runner.RunWith;
11
+import org.mockito.InjectMocks;
12
+import org.mockito.Mock;
13
+import org.mockito.MockitoAnnotations;
14
+import org.springframework.boot.test.context.SpringBootTest;
15
+import org.springframework.http.MediaType;
16
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
17
+import org.springframework.test.context.web.WebAppConfiguration;
18
+import org.springframework.test.web.servlet.MockMvc;
19
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
20
+
21
+import java.util.ArrayList;
22
+import java.util.List;
23
+
24
+import static org.hamcrest.Matchers.hasSize;
25
+import static org.hamcrest.Matchers.is;
26
+import static org.mockito.Mockito.*;
27
+import static org.mockito.Mockito.verifyNoMoreInteractions;
28
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
29
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
30
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
31
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
32
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
33
+
34
+
35
+// ========== Looked further into the readme. Testing Controller the 'right' way now =========//
36
+
37
+@WebAppConfiguration
38
+@SpringBootTest
39
+@RunWith(SpringJUnit4ClassRunner.class)
40
+public class PersonControllerTestMVC {
41
+    List<Person> list;
42
+    Person testPerson = new Person("Test", "Person");
43
+    private MockMvc mockMvc;
44
+
45
+    @Mock
46
+    private PersonService personService;
47
+
48
+    @InjectMocks
49
+    private PersonController personController;
50
+
51
+    @Before
52
+    public void init(){
53
+        list = new ArrayList<>();
54
+        list.add(testPerson);
55
+
56
+        MockitoAnnotations.initMocks(this);
57
+        mockMvc = MockMvcBuilders
58
+                .standaloneSetup(personController)
59
+                .build();
60
+    }
61
+
62
+    // =================== Get All Users =================== //
63
+
64
+    @Test
65
+    public void testGetPersonList() throws Exception {
66
+        when(personService.getPersonList()).thenReturn(list);
67
+
68
+        mockMvc.perform(get("/people"))
69
+                .andExpect(status().isOk())
70
+                .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
71
+                .andExpect(jsonPath("$", hasSize(1)))
72
+                .andExpect(jsonPath("$[0].firstName", is("Test")))
73
+                .andExpect(jsonPath("$[0].lastName",is("Person")));
74
+
75
+        verify(personService,times(1)).getPersonList();
76
+        verifyNoMoreInteractions(personService);
77
+    }
78
+
79
+    // ======================== Get User By ID ======================== //
80
+
81
+    @Test
82
+    public void testGetPersonById() throws Exception {
83
+        when(personService.getPersonById(1L)).thenReturn(testPerson);
84
+
85
+        mockMvc.perform(get("/people/{id}",1))
86
+                .andExpect(status().isOk())
87
+                .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
88
+                .andExpect(jsonPath("$.firstName",is("Test")))
89
+                .andExpect(jsonPath("$.lastName",is("Person")));
90
+
91
+        verify(personService,times(1)).getPersonById(1L);
92
+        verifyNoMoreInteractions(personService);
93
+    }
94
+
95
+    @Test
96
+    public void testGetPersonById_fail_404_notFound() throws Exception {
97
+        when(personService.getPersonById(2L)).thenReturn(null);
98
+
99
+        mockMvc.perform(get("/people/{id}",2))
100
+                .andExpect(status().isNotFound());
101
+
102
+        verify(personService, times(1)).getPersonById(2L);
103
+        verifyNoMoreInteractions(personService);
104
+    }
105
+
106
+    // ======================== Create Person ======================== //
107
+
108
+    @Test
109
+    public void testCreatePerson() throws Exception {
110
+        when(personService.savePerson(testPerson)).thenReturn(testPerson);
111
+
112
+        mockMvc.perform(post("/people")
113
+                    .contentType(MediaType.APPLICATION_JSON)
114
+                    .content(asJsonString(testPerson)))
115
+                .andExpect(status().isCreated());
116
+
117
+        verify(personService,times(1)).savePerson(testPerson);
118
+        verifyNoMoreInteractions(personService);
119
+    }
120
+
121
+    // ======================== Update Person ======================== //
122
+
123
+    @Test
124
+    public void testUpdatePerson() throws Exception {
125
+        when(personService.savePerson(testPerson)).thenReturn(testPerson);
126
+
127
+        mockMvc.perform(put("/people/{id}",1)
128
+                .contentType(MediaType.APPLICATION_JSON)
129
+                .content(asJsonString(testPerson)))
130
+                .andExpect(status().isOk());
131
+
132
+        verify(personService, times(1)).savePerson(testPerson);
133
+        verifyNoMoreInteractions(personService);
134
+    }
135
+
136
+    // ======================== Delete Person ======================== //
137
+
138
+    @Test
139
+    public void testDeletePerson() throws Exception {
140
+        doNothing().when(personService).deletePerson(1L);
141
+
142
+        mockMvc.perform(delete("/people/{id}",1))
143
+                .andExpect(status().isNoContent());
144
+
145
+        verify(personService, times(1)).deletePerson(1L);
146
+        verifyNoMoreInteractions(personService);
147
+    }
148
+
149
+
150
+    public static String asJsonString(final Object obj) {
151
+        try {
152
+            final ObjectMapper mapper = new ObjectMapper();
153
+            return mapper.writeValueAsString(obj);
154
+        } catch (Exception e) {
155
+            throw new RuntimeException(e);
156
+        }
157
+    }
158
+}