티스토리 뷰

URI의 path를 다양한 형태로 매핑하는 예제를 만들어 봅니다. 

 

java 

@Slf4j
@RestController
@RequestMapping("/controller/path")
public class PathVariableAPIController {

    /**
     * 단순 매핑 테스트 
     * @return
     */
    @GetMapping("/{id}")
    public ResponseEntity<String> simple(@PathVariable String id) {
        log(id);
        return ResponseEntity.ok(id);
    }

    /**
     * required false test 
     * @param id
     * @return
     */
    @GetMapping(value = { "/requiredfalse", "/requiredfalse/{id}"})
    public ResponseEntity<String> requiredfalse(@PathVariable(required = false) String id) {
        return simple(id);
    }
    
    /**
     * optional test 
     * @param id
     * @return
     */
    @GetMapping(value = { "/optional", "/optional/{id}"})
    public ResponseEntity<String> requiredfalseOptional(@PathVariable(required = false) Optional<String> id) {
        String path = id.orElse("none");
        log(path);
        return ResponseEntity.ok(path);
    }
    
    /**
     * pathVariable 복수개인 경우 테스트 
     * @param id
     * @param name
     * @return
     */
    @GetMapping("/{id}/{name}")
    public ResponseEntity<Map<String, String>> multiplePaths(@PathVariable String id, @PathVariable String name) {
        Map<String, String> paths = new HashMap<>();
        paths.put("id", id);
        paths.put("name", name);
        log(paths.toString());
        return ResponseEntity.ok(paths);
    }

    /**
     * pathVariable을 Map으로 받는 경우 
     * @param paths
     * @return
     */
    @GetMapping("/map/{id}/{name}")
    public ResponseEntity<Map<String, String>> multipleMapPaths(@PathVariable Map<String, String> paths) {
        log(paths.toString());
        return ResponseEntity.ok(paths);
    }
    
    /**
     * pathVariable을 Object로 받는 경우 
     * @param paths
     * @return
     */
    @GetMapping("/object/{id}/{name}")
    public ResponseEntity<MappingParams> multipleObjectPaths(MappingParams paths) {
        log(paths.toString());
        return ResponseEntity.ok(paths);
    }
    
    private void log(String message) {
        log.debug("path :" + message);
    }
    @Getter
    @Setter
    @ToString
    public static class MappingParams {
        private String id;
        private String name;
    }
}

test

@WebMvcTest(PathVariableAPIController.class)
class PathVariableAPIControllerTest {

    @Autowired 
    private MockMvc mockMvc;

    private static final String ROOT_URI = "/controller/path";

    /**
     * 매핑 테스트 
     * @throws Exception
     */
    @ParameterizedTest
    @CsvSource({
        ROOT_URI+"/test,test"
        , ROOT_URI+"/requiredfalse/test,test"
        , ROOT_URI+"/requiredfalse,"
        , ROOT_URI+"/optional/test,test"
        , ROOT_URI+"/optional,none"
        })
    void simpleMapping(String uri, String expected) throws Exception {
        MockHttpServletRequestBuilder mrbuilder = MockMvcRequestBuilders.get(uri).contentType(MediaType.APPLICATION_JSON);
        if(expected == null) expected = "";
        MvcResult result = mockMvc.perform(mrbuilder)
                .andDo(print())
                .andExpect(status().isOk())
                .andReturn();
        String content = result.getResponse().getContentAsString();
        assertThat(content).isEqualTo(expected);
    }

    /**
     * multiple path 테스트   
     * @throws Exception
     */
    @ParameterizedTest
    @CsvSource({
        ROOT_URI+"/test/eblo,test,eblo"
        , ROOT_URI+"/map/test/eblo,test,eblo"
        , ROOT_URI+"/object/test/eblo,test,eblo"
        })
    void multiplePaths(String uri, String id, String name) throws Exception {
        mockMvc.perform(MockMvcRequestBuilders.get(uri)
                .contentType(MediaType.APPLICATION_JSON))
                .andDo(print())
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.name").value(name))
                .andExpect(jsonPath("$.id").value(id));
    }

}

git : https://github.com/kkaok/study-springboot/blob/main/src/main/java/eblo/study/springboot/controller/PathVariableAPIController.java

'study > springboot' 카테고리의 다른 글

011. Controller @InitBinder  (0) 2022.05.14
010. Request parameter 처리  (0) 2022.05.14
008. Controller request mapping  (0) 2022.05.11
007. 기본 설정 추가 및 실행  (0) 2022.05.11
006. 사용자 배너 추가  (0) 2022.05.11
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/11   »
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
글 보관함