포스트

Spring Boot Test - Interceptor 테스트

Custom Interceptor 테스트 🤔

실행되는 interceptor의 메서드를 확인하는 unit(mock mvc) 테스트와 interceptor 내부 로직 검증을 확인하는 unit(mock) 테스트 2가지로 구분하여 작성했다. ‘로직과 조건이 복잡해진다면 괜찮은 테스트가 되지 않을까??’ ‘라는 생각을 해보면서 기록


TaskInterceptor

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@RequiredArgsConstructor  
@Component  
public class TaskInterceptor implements HandlerInterceptor {  
    private final TaskService taskService;  
      
      
    @Override  
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {  
  
        if (request.getRequestURI().equals("/task")) {  
            taskService.findById(1);  
            return true;  
        }  
        return false;  
    }  
}

WebConfig

1
2
3
4
5
6
7
8
9
10
11
@RequiredArgsConstructor  
@Configuration  
public class WebConfig implements WebMvcConfigurer {  
    private final TaskInterceptor interceptor;  
      
  
    @Override  
    public void addInterceptors(InterceptorRegistry registry) {  
        registry.addInterceptor(interceptor);  
    }  
}

ApiController

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
/**
* TaskController.java
*/
@RestController  
public class TaskController {  
    @GetMapping("/task")  
    public String task() {  
        return "this is task";  
    }  
    @GetMapping("/other")  
    public String other() {  
        return "this is other";  
    }  
    @GetMapping("/test")  
    public String test() {  
        return "this is test";  
    }  
}


/**
* TestController.java
*/
@RestController  
public class TestController {  
    @GetMapping("/task-test")  
    public String taskTest() {  
        return "this is test task";  
    }  
    @GetMapping("/other-test")  
    public String other() {  
        return "this is test other";  
    }  
    @GetMapping("/test-test")  
    public String test() {  
        return "this is test test";  
    }  
}


TaskInterceptor Unit (mvc) Test

api 접근시 interceptor 메서드 실행 검증을 위한 테스트

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
  
@DisplayName("interceptor mvc test")  
@WebMvcTest  
class TaskInterceptorMvcTest {  

    @Autowired MockMvc mvc;  
      
    @MockBean TaskInterceptor taskInterceptor;  
      
      
    @DisplayName("/task end-point 접근")  
    @Test  
    void running_test_end_point_with_task() throws Exception {  
        // given  
        BDDMockito.given(taskInterceptor.preHandle(any(), any(), any())).willReturn(true);  
          
          
        // when  
        mvc.perform(MockMvcRequestBuilders.get("/task"))  
                .andExpect(MockMvcResultMatchers.status().isOk());  
          
          
        // then  
        BDDMockito.then(taskInterceptor).should(times(1)).preHandle(any(), any(), any());  
        BDDMockito.then(taskInterceptor).should(times(1)).postHandle(any(), any(), any(), any());  
    }  


    @ParameterizedTest(name = "{0} end-point 접근")  
    @ValueSource(strings = {  
            "/other",  
            "/test",  
            "/task-test",  
            "/other-test",  
            "/test-test"  
    })  
    void running_test_end_point_without_task(String uri) throws Exception {  
        // given  
        BDDMockito.given(taskInterceptor.preHandle(any(), any(), any())).willReturn(false);  
          
          
        // when  
        mvc.perform(MockMvcRequestBuilders.get(uri))  
                .andExpect(MockMvcResultMatchers.status().isOk());  
          
          
        // then  
        BDDMockito.then(taskInterceptor).should(times(1)).preHandle(any(), any(), any());  
        BDDMockito.then(taskInterceptor).should(times(0)).postHandle(any(), any(), any(), any());  
    }  
}

TaskInterceptor Unit (mock) Test

interceptor 내부 실행 로직 검증을 위한 테스트

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
@DisplayName("interceptor unit test")  
@ExtendWith(MockitoExtension.class)  
class TaskInterceptorUnitTest {  
  
    @InjectMocks TaskInterceptor taskInterceptor;  
      
    @Mock TaskService taskService;  
      
    @Mock HttpServletRequest request;  
    @Mock HttpServletResponse response;  
    @Mock Object handler;  
      
      
    @DisplayName("/task end-point 접근")  
    @Test  
    void only_task() throws Exception {  
        // given  
        BDDMockito.given(request.getRequestURI()).willReturn("/task");  
          
          
        // when  
        boolean resultPreHandle = taskInterceptor.preHandle(request, response, handler);  
          
          
        // then  
        assertTrue(resultPreHandle);  
        BDDMockito.then(taskService).should(times(1)).findById(anyLong());  
    }  
    
    
    @ParameterizedTest(name = "{0} end-point 접근")  
    @ValueSource(strings = {  
            "/other",  
            "/test",  
            "/task-test",  
            "/other-test",  
            "/test-test"  
    })  
    void without_task(String uri) throws Exception {  
        // given  
        BDDMockito.given(request.getRequestURI()).willReturn(uri);  
          
          
        // when  
        boolean resultPreHandle = taskInterceptor.preHandle(request, response, handler);  
          
          
        // then  
        assertFalse(resultPreHandle);  
        BDDMockito.then(taskService).should(times(0)).findById(anyLong());  
    }  
}




참고한 사이트

이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.