forked from Pragmatists/testing-examples
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathContactControllerTest.java
More file actions
62 lines (50 loc) · 2.09 KB
/
ContactControllerTest.java
File metadata and controls
62 lines (50 loc) · 2.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package com.pik.contact.api;
import com.pik.contact.Application;
import com.pik.contact.domain.Contact;
import com.pik.contact.repository.ContactRepository;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.http.MediaType.APPLICATION_JSON;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@DirtiesContext
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
@WebAppConfiguration
public class ContactControllerTest {
@Autowired
ContactRepository repository;
@Autowired
ContactController controller;
@Before
public void setup() {
repository.deleteAll();
mockMvc = buildMockMvc(controller);
}
private MockMvc mockMvc;
private MockMvc buildMockMvc(Object... controllers) {
return MockMvcBuilders
.standaloneSetup(controllers)
.build();
}
@Test
public void should_save_contact() throws Exception {
MvcResult result = mockMvc.perform(post("/rest/contacts").contentType(APPLICATION_JSON)
.content("{\"name\":\"John\",\"fullName\":\"Doe\"}"))
.andExpect(status().isCreated())
.andReturn();
Contact contact = repository.findById(result.getResponse().getContentAsString()).orElse(null);
assertThat(contact.getName()).isEqualTo("John");
assertThat(contact.getFullName()).isEqualTo("Doe");
}
}