2014-03-04 2 views
1

- 위는 스프링 MVC 컨트롤러 메서드의 반환 형식을 JUnit을하는 방법 내 스프링 MVC 컨트롤러에서의 JUnit을하고있는 중이 야

public class ControllerTest { 

    private MockMvc mockMvc; 

    @Before 
    public void setup() throws Exception { 
    this.mockMvc = standaloneSetup(new Controller()).build(); 
    } 

    @Test 
    public void test01_Index() { 

    try { 
     mockMvc.perform(get("/index")).andExpect(status().isOk()); 

    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
    } 
} 

- 아래

@RequestMapping(value = "index", method = RequestMethod.GET) 
    public HashMap<String, String> handleRequest() { 
    HashMap<String, String> model = new HashMap<String, String>(); 
    String name = "Hello World"; 
    model.put("greeting", name); 

    return model; 
} 

그리고는 위의 방법에 대한 내 JUnit을하다 junit 잘 작동합니다.

하지만 내 질문은 handleRequest의 반환 유형을 어떻게 키와 값 쌍으로 HashMap을 반환합니다 .. 어떻게합니까 Hello World을 반환하는지 확인하십시오. 그걸 할 수있는 방법이 있습니까?

답변

2

서버 측 코드를 테스트하기 위해 MockMvc를 사용하여 참조하는 at the examples in the Spring reference manual을 살펴보십시오. 당신은 JSON 응답을 반환하는 가정 :

mockMvc.perform(get("/index")) 
    .andExpect(status().isOk()) 
    .andExpect(content().contentType("application/json")) 
    .andExpect(jsonPath("$.greeting").value("Hello World")); 

을 그건 그렇고 - 잡을 당신이 그 예외를 무시하고 테스트를 실패하는 것을 방지하고자하지 않는 한 @Test 방법에 예외를 삼키는 않았다. 컴파일러에서 테스트 메서드가 예외를 throw하는 메서드를 호출했으나 처리하지 못했다고 불평하는 경우 메서드 서명을 throws Exception으로 변경하면됩니다.

+0

고마워 .. 그게 .. 내 'handleRequest' 메쏘드가 문자열 매개 변수를 취한다고 가정하면, 내 junit 테스트에서 어떻게 통과시킬 수 있을까? – AKIWEB

+0

@AKIWEB는 링크 된 문서에서 다룹니다. "요청 수행"섹션을보십시오. –

관련 문제