Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
4.7 kB
2
Indexable
Never
	@PutMapping("/{id}")
	@PreAuthorize("hasRole('USER') or hasRole('ADMIN')")
	public ResponseEntity<Post> updatePost(@PathVariable(name = "id") Long id,
			@Valid @RequestBody PostRequest newPostRequest, @CurrentUser UserPrincipal currentUser) {
		Post post = postService.updatePost(id, newPostRequest, currentUser);

		return new ResponseEntity< >(post, HttpStatus.OK);
	}
///////////////////////////////////////////////////////////////////

@WebMvcTest(YourControllerClass.class)
public class YourControllerClassTest {

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private PostService postService;

    @Test
    public void testUpdatePostWithSingleComment() throws Exception {
        Long postId = 1L;
        PostRequest mockPostRequest = new PostRequest("New Post Content");
        UserPrincipal mockUserPrincipal = new UserPrincipal(1L, "testuser");

        Comment comment = new Comment("Single Comment");

        Post updatedPost = new Post(postId, "New Post Content", mockUserPrincipal.getUser());
        updatedPost.setComment(comment);

        Mockito.when(postService.updatePost(postId, mockPostRequest, mockUserPrincipal))
                .thenReturn(updatedPost);

        mockMvc.perform(MockMvcRequestBuilders.put("/{id}", postId)
                .contentType(MediaType.APPLICATION_JSON)
                .content("{\"content\": \"New Post Content\"}")
                .header("Authorization", "Bearer <your_token_here>"))
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andExpect(MockMvcResultMatchers.jsonPath("$.id").value(postId))
                .andExpect(MockMvcResultMatchers.jsonPath("$.content").value("New Post Content"))
                .andExpect(MockMvcResultMatchers.jsonPath("$.comment.text").value("Single Comment"));
               // .andExpect(MockMvcResultMatchers.jsonPath("$.comments[1].text").value("Comment 2"));// if include list comment


        Mockito.verify(postService).updatePost(postId, mockPostRequest, mockUserPrincipal);
    }
}



////////////////////////////////////////////
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.slf4j.Logger;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;

@WebMvcTest(TssApiController.class)
public class TssApiControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private TssService tssService;

    @Mock
    private Logger logger;

    @Captor
    private ArgumentCaptor<String> logCaptor;

    @Test
    public void testApplyCustomerFile() throws Exception {
        // Chuẩn bị dữ liệu đầu vào cho test case
        MockMultipartFile file = new MockMultipartFile("customerFile", "customer.xml",
                MediaType.TEXT_XML_VALUE, "<customer>...</customer>".getBytes());

        // Gọi phương thức controller cần được kiểm tra
        mockMvc.perform(MockMvcRequestBuilders.multipart("/v1/tss/customer")
                .file(file))
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON))
                .andDo(print());

        // Kiểm tra rằng phương thức trong service đã được gọi với đúng tham số
        Mockito.verify(tssService).applyCustomerFile(any(), eq(file));

        // Kiểm tra rằng log.info đã được gọi với đúng tham số
        Mockito.verify(logger).info(logCaptor.capture());

        // Lấy giá trị của log.info
        String logInfoMessage = logCaptor.getValue();

        // Kiểm tra xem log.info có bao gồm đúng thông tin về name và size không
        assertThat(logInfoMessage).contains(file.getOriginalFilename());
        assertThat(logInfoMessage).contains(String.valueOf(file.getSize()));
    }
}
Leave a Comment