Skip to content

Commit 08c5135

Browse files
committed
add
1 parent 2039d41 commit 08c5135

File tree

2 files changed

+89
-129
lines changed

2 files changed

+89
-129
lines changed
Lines changed: 27 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
package exercise;
22

3+
import java.net.URI;
34
import java.util.List;
45
import java.util.Optional;
56

@@ -13,14 +14,16 @@
1314
import org.springframework.web.bind.annotation.PostMapping;
1415
import org.springframework.web.bind.annotation.PutMapping;
1516
import org.springframework.web.bind.annotation.RequestBody;
17+
import org.springframework.web.bind.annotation.RequestParam;
1618
import org.springframework.web.bind.annotation.RestController;
1719

1820
import exercise.model.Post;
21+
import exercise.Data;
1922

2023
@SpringBootApplication
2124
@RestController
2225
public class Application {
23-
26+
// Хранилище добавленных постов
2427
private List<Post> posts = Data.getPosts();
2528

2629
public static void main(String[] args) {
@@ -29,45 +32,43 @@ public static void main(String[] args) {
2932

3033
// BEGIN
3134
@GetMapping("/posts")
32-
public ResponseEntity<List<Post>> index() {
35+
public ResponseEntity<List<Post>> getAllPosts() {
36+
int totalCount = posts.size();
3337
return ResponseEntity.ok()
34-
.header("X-Total-Count", String.valueOf(posts.size()))
38+
.header("X-Total-Count", String.valueOf(totalCount))
3539
.body(posts);
3640
}
3741

3842
@GetMapping("/posts/{id}")
39-
public ResponseEntity<Post> show(@PathVariable String id) {
40-
Optional<Post> foundPost = posts.stream()
41-
.filter(p -> p.getId().equals(id))
43+
public ResponseEntity<Post> getPostById(@PathVariable Long id) {
44+
Optional<Post> postOptional = posts.stream()
45+
.filter(post -> post.getId().equals(id))
4246
.findFirst();
43-
return ResponseEntity.of(foundPost);
47+
48+
if (postOptional.isPresent()) {
49+
return ResponseEntity.ok(postOptional.get());
50+
} else {
51+
return ResponseEntity.notFound().build();
52+
}
4453
}
4554

4655
@PostMapping("/posts")
47-
public ResponseEntity<Post> create(@RequestBody Post post) {
56+
public ResponseEntity<Post> createPost(@RequestBody Post post) {
4857
posts.add(post);
49-
return ResponseEntity.status(HttpStatus.CREATED).body(post);
58+
return ResponseEntity.status(HttpStatus.CREATED)
59+
.location(URI.create("/posts/" + post.getId()))
60+
.body(post);
5061
}
5162

5263
@PutMapping("/posts/{id}")
53-
public ResponseEntity<Post> update(@PathVariable String id, @RequestBody Post post) {
54-
Optional<Post> ifPost = posts.stream()
55-
.filter(p -> p.getId().equals(id))
56-
.findFirst();
57-
if (ifPost.isPresent()) {
58-
Post foundPost = ifPost.get();
59-
foundPost.setId(post.getId());
60-
foundPost.setTitle(post.getTitle());
61-
foundPost.setBody(post.getBody());
62-
return ResponseEntity.ok().body(post);
63-
} else {
64-
return ResponseEntity.status(HttpStatus.NO_CONTENT).body(post);
64+
public ResponseEntity<Post> updatePost(@PathVariable Long id, @RequestBody Post updatedPost) {
65+
for (int i = 0; i < posts.size(); i++) {
66+
if (posts.get(i).getId().equals(id)) {
67+
posts.set(i, updatedPost);
68+
return ResponseEntity.ok(updatedPost);
69+
}
6570
}
71+
return ResponseEntity.notFound().build();
6672
}
6773
// END
68-
69-
@DeleteMapping("/posts/{id}")
70-
public void destroy(@PathVariable String id) {
71-
posts.removeIf(p -> p.getId().equals(id));
72-
}
7374
}
Lines changed: 62 additions & 103 deletions
Original file line numberDiff line numberDiff line change
@@ -1,122 +1,81 @@
11
package exercise;
22

3-
import org.junit.jupiter.api.Test;
4-
import org.junit.jupiter.api.BeforeEach;
5-
import org.junit.jupiter.api.TestMethodOrder;
6-
import org.junit.jupiter.api.MethodOrderer;
7-
import org.junit.jupiter.api.Order;
8-
9-
import org.springframework.beans.factory.annotation.Autowired;
10-
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
11-
import org.springframework.boot.test.context.SpringBootTest;
12-
import org.springframework.test.web.servlet.MockMvc;
13-
import org.springframework.http.MediaType;
14-
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
15-
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
16-
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
17-
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
18-
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
19-
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
20-
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
21-
22-
import java.nio.charset.StandardCharsets;
23-
import java.util.ArrayList;
243
import java.util.List;
4+
import java.util.Optional;
5+
import java.util.stream.Collectors;
6+
7+
import org.springframework.boot.SpringApplication;
8+
import org.springframework.boot.autoconfigure.SpringBootApplication;
9+
import org.springframework.http.HttpStatus;
10+
import org.springframework.http.ResponseEntity;
11+
import org.springframework.web.bind.annotation.DeleteMapping;
12+
import org.springframework.web.bind.annotation.GetMapping;
13+
import org.springframework.web.bind.annotation.PathVariable;
14+
import org.springframework.web.bind.annotation.PostMapping;
15+
import org.springframework.web.bind.annotation.PutMapping;
16+
import org.springframework.web.bind.annotation.RequestBody;
17+
import org.springframework.web.bind.annotation.RestController;
18+
import org.springframework.http.MediaType;
19+
import org.springframework.web.util.UriComponentsBuilder;
2520

26-
import org.springframework.web.context.WebApplicationContext;
27-
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
28-
import com.fasterxml.jackson.databind.ObjectMapper;
2921
import exercise.model.Post;
22+
import exercise.Data;
3023

31-
@SpringBootTest
32-
@AutoConfigureMockMvc
33-
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
34-
class ApplicationTest {
35-
36-
@Autowired
37-
private WebApplicationContext wac;
24+
@SpringBootApplication
25+
@RestController
26+
class Application {
27+
// Хранилище добавленных постов
28+
private List<Post> posts = Data.getPosts();
3829

39-
@Autowired
40-
private MockMvc mockMvc;
41-
42-
@Autowired
43-
private ObjectMapper om;
44-
45-
@BeforeEach
46-
public void setUp() throws Exception {
47-
mockMvc = MockMvcBuilders.webAppContextSetup(wac)
48-
.defaultResponseCharacterEncoding(StandardCharsets.UTF_8)
49-
.build();
50-
Post testPost = new Post("test-post", "Test post", "Test body");
51-
Application.setPosts(new ArrayList<>(List.of(testPost)));
30+
public static void main(String[] args) {
31+
SpringApplication.run(Application.class, args);
5232
}
5333

54-
@Order(1)
55-
@Test
56-
public void testShow() throws Exception {
57-
mockMvc.perform(get("/posts/test-post"))
58-
.andExpect(status().isOk());
34+
// BEGIN
35+
@GetMapping("/posts")
36+
public ResponseEntity<List<Post>> getAllPosts() {
37+
int totalCount = posts.size();
38+
return ResponseEntity.ok()
39+
.header("X-Total-Count", String.valueOf(totalCount))
40+
.body(posts);
5941
}
6042

61-
@Test
62-
public void testCreatePost() throws Exception {
63-
var post = new Post("another-post", "another post", "body");
64-
65-
var request = post("/posts")
66-
.contentType(MediaType.APPLICATION_JSON)
67-
.content(om.writeValueAsString(post));
68-
69-
mockMvc.perform(request)
70-
.andExpect(status().isCreated())
71-
.andExpect(content().json(om.writeValueAsString(post)));
43+
@GetMapping("/posts/{id}")
44+
public ResponseEntity<Post> getPostById(@PathVariable String id) {
45+
Optional<Post> postOptional = posts.stream()
46+
.filter(post -> post.getId().equals(id))
47+
.findFirst();
48+
49+
if (postOptional.isPresent()) {
50+
return ResponseEntity.ok(postOptional.get());
51+
} else {
52+
return ResponseEntity.notFound().build();
53+
}
7254
}
7355

74-
@Test
75-
public void testIndex() throws Exception {
76-
mockMvc.perform(get("/posts"))
77-
.andExpect(status().isOk())
78-
.andExpect(header().string("X-Total-Count", "1"));
56+
@PostMapping("/posts")
57+
public ResponseEntity<Post> createPost(@RequestBody Post post) {
58+
posts.add(post);
59+
return ResponseEntity.status(HttpStatus.CREATED)
60+
.location(UriComponentsBuilder.fromPath("/posts/{id}").buildAndExpand(post.getId()).toUri())
61+
.body(post);
7962
}
8063

81-
@Test
82-
public void testShowUnknown() throws Exception {
83-
mockMvc.perform(get("/posts/unknown-post"))
84-
.andExpect(status().isNotFound());
64+
@PutMapping("/posts/{id}")
65+
public ResponseEntity<Post> updatePost(@PathVariable String id, @RequestBody Post updatedPost) {
66+
for (int i = 0; i < posts.size(); i++) {
67+
if (posts.get(i).getId().equals(id)) {
68+
posts.set(i, updatedPost);
69+
return ResponseEntity.ok(updatedPost);
70+
}
71+
}
72+
return ResponseEntity.notFound().build();
8573
}
8674

87-
@Test
88-
public void testUpdatePost() throws Exception {
89-
var post = new Post("test-post", "new title", "new body");
90-
91-
var request = put("/posts/test-post")
92-
.contentType(MediaType.APPLICATION_JSON)
93-
.content(om.writeValueAsString(post));
94-
95-
mockMvc.perform(request)
96-
.andExpect(status().isOk())
97-
.andExpect(content().json(om.writeValueAsString(post)));
98-
99-
mockMvc.perform(get("/posts/test-post"))
100-
.andExpect(status().isOk())
101-
.andExpect(content().json(om.writeValueAsString(post)));
102-
}
103-
104-
@Test
105-
public void testUpdateUnknownPost() throws Exception {
106-
var post = new Post("unknown-post", "new title", "new body");
107-
108-
var request = put("/posts/unknown-post")
109-
.contentType(MediaType.APPLICATION_JSON)
110-
.content(om.writeValueAsString(post));
111-
112-
mockMvc.perform(request)
113-
.andExpect(status().isNotFound());
114-
}
115-
116-
@Test
117-
public void testDelete() throws Exception {
118-
mockMvc.perform(delete("/posts/test-post"))
119-
.andExpect(status().isOk());
120-
75+
@DeleteMapping("/posts/{id}")
76+
public ResponseEntity<Void> deletePost(@PathVariable String id) {
77+
posts.removeIf(post -> post.getId().equals(id));
78+
return ResponseEntity.ok().build();
12179
}
80+
// END
12281
}

0 commit comments

Comments
 (0)