Skip to content

Commit

Permalink
Adding new test scenarios for the controller
Browse files Browse the repository at this point in the history
  • Loading branch information
alexertech committed Oct 25, 2023
1 parent 2d80d58 commit 3e707e4
Showing 1 changed file with 58 additions and 4 deletions.
62 changes: 58 additions & 4 deletions src/test/java/com/example/blog/controller/PostControllerTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,13 @@
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import static org.mockito.Mockito.*;

import java.util.Optional;

import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;


@SpringBootTest
@AutoConfigureMockMvc
Expand Down Expand Up @@ -62,4 +62,58 @@ void getPostById_returnsPost() throws Exception {
mockMvc.perform(get("/posts/1"))
.andExpect(status().isOk());
}

@Test
void createPost_emptyTitle_returnsBadRequest() throws Exception {
Post post = new Post();
post.setTitle("");
post.setBody("Test Body");

mockMvc.perform(post("/posts")
.contentType(MediaType.APPLICATION_JSON)
.content(new ObjectMapper().writeValueAsString(post)))
.andExpect(status().isBadRequest());
}

@Test
void createPost_emptyBody_returnsBadRequest() throws Exception {
Post post = new Post();
post.setTitle("Test Title");
post.setBody("");

mockMvc.perform(post("/posts")
.contentType(MediaType.APPLICATION_JSON)
.content(new ObjectMapper().writeValueAsString(post)))
.andExpect(status().isBadRequest());
}

@Test
void updatePost_returnsOk() throws Exception {
Post post = new Post();
post.setId(1L);
post.setTitle("Updated Title");
post.setBody("Updated Body");

when(postRepository.findById(1L)).thenReturn(Optional.of(post));
when(postRepository.save(post)).thenReturn(post);

mockMvc.perform(put("/posts/1")
.contentType(MediaType.APPLICATION_JSON)
.content(new ObjectMapper().writeValueAsString(post)))
.andExpect(status().isOk());
}

@Test
void deletePost_returnsOk() throws Exception {
Post post = new Post();
post.setId(1L);
post.setTitle("Test Title");
post.setBody("Test Body");

when(postRepository.findById(1L)).thenReturn(Optional.of(post));
doNothing().when(postRepository).delete(post);

mockMvc.perform(delete("/posts/1"))
.andExpect(status().isOk());
}
}

0 comments on commit 3e707e4

Please sign in to comment.