ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 2022.07.06 Spring Mock 사용해보기
    Spring Boot 2022. 7. 6. 21:41
    반응형

    오늘은 Spring Mock을 사용해보았습니다.

    Mock을 사용하면 좋은 점

    Mock을 사용하면 그냥 Controller에 테스트를 하는 것보다 의존성이 단절시킬 수 있어서 쉽게 테스트할 수 있습니다.

    (참고: https://elevatingcodingclub.tistory.com/61)

     

    저도 오늘 처음 Mock을 사용해서 사실 저 좋은 점을 실제로 체감하지는 못했습니다...

     

    Mock 적용 테스트

    제가 Spring으로 전에 제작해본 todoList api를 Mock으로 테스트 해보았습니다.

    @WebMvcTest(TodoController.class)
    class TodoControllerTest {
    
        @Autowired
        MockMvc mvc;
    
        @MockBean
        TodoService service;
    
        private TodoEntity expected;
    
    
        @BeforeEach
        void setUp() {
            this.expected = new TodoEntity();
    
            this.expected.setId(123L);
            this.expected.setTitle("TestTitle");
            this.expected.setOrder(0L);
            this.expected.setCompleted(false);
    
        }
    
        @Test
        void create() throws Exception {
            when(this.service.add(any(TodoRequest.class)))
                    .then(i -> {
                        TodoRequest request = i.getArgument(0, TodoRequest.class);
                        return new TodoEntity(this.expected.getId(), this.expected.getTitle(), this.expected.getOrder(), this.expected.getCompleted());
                    });
            TodoRequest request = new TodoRequest();
            request.setTitle("ANY TITLE");
    
            ObjectMapper mapper = new ObjectMapper();
            String content = mapper.writeValueAsString(request);
    
            // request를 body에 넣어주어야하지만 직접적으로 넣어줄 수 없어서
            // ObjectMapper를 사용하였음.
            this.mvc.perform(post("/").contentType(MediaType.APPLICATION_JSON).content(content))
                    .andExpect(status().isOk())
                    .andExpect(jsonPath("$.title").value("ANY TITLE"));
        }
    }

    마치며

    오늘은 사이드 프로젝트를 진행하지 못해서 조금 아쉽지만 몸상태가 좋지 않은 관계로 하루 쉬어가겠습니다.

    : )

    반응형

    'Spring Boot' 카테고리의 다른 글

    Spring Boot - SLF4J로 Log남기기  (0) 2023.07.01

    댓글

Designed by Tistory.