2010-11-05 147 views
2

如何爲使用註釋@RequestParam的Spring MVC控制器創建單元測試?我已經爲在controllerrequest方法中使用HttpServletRequest對象的控制器創建了junit測試,但是我正在尋找一種使用@RequestParam測試控制器的方法。使用註釋的Spring MVC控制器的單元測試@RequestParam

感謝

@RequestMapping("/call.action") 

public ModelAndView getDBRecords(@RequestParam("id") String id) { 

    Employee employee = service.retrieveEmployee(id); 

} 
+0

在這篇文章請看:http://stackoverflow.com/questions/861089/testing-spring-mvc-annotation-mapppings – McStretch 2010-11-05 18:52:28

回答

11

一個這種風格控制器的魅力是你的單元測試並不需要擔心的請求映射的機制。他們可以直接對目標代碼進行測試,而不會與請求和響應對象混淆。

所以編寫你的單元測試就好像它只是任何其他類一樣,而忽略註釋。換句話說,請從您的測試中調用getDBRecords()並傳遞id參數。記住,你不需要對Spring本身進行單元測試,你可以假設它是有效的。

還有另一類測試(「功能性」或「接受」測試),它在部署後測試應用程序(使用WebDriver,Selenium,HtmlUnit等)。 這個是測試你的映射註釋在做這項工作的地方。

0

或者,你可以使用 _request =新MockHttpServletRequest();

and _request.setAttribute(「key」,「value」);

0

使用集成測試(谷歌Spring MVC的集成測試)

有點兒這個

import org.junit.Assert; 
import org.junit.Test; 
import org.junit.runner.RunWith; 
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.beans.factory.annotation.Value; 
import org.springframework.boot.test.IntegrationTest; 
import org.springframework.boot.test.SpringApplicationContextLoader; 
import org.springframework.http.HttpStatus; 
import org.springframework.http.ResponseEntity; 
import org.springframework.test.context.ContextConfiguration; 
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 
import org.springframework.test.context.web.WebAppConfiguration; 
import org.springframework.web.client.RestTemplate; 
import org.springframework.web.context.WebApplicationContext; 

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(classes = YourApplication.class, loader = SpringApplicationContextLoader.class) 
@WebAppConfiguration 
@IntegrationTest("server.port:0") 
public class SampleControllerTest { 

    @Value("${local.server.port}") 
    protected int port; 

    @Autowired 
    protected WebApplicationContext context; 

    private RestTemplate restTemplate = new RestTemplate(); 

    @Test 
    public void returnsValueFromDb() { 
     // you should run mock db before 
     String id = "a0972ca1-0870-42c0-a590-be441dca696f"; 
     String url = "http://localhost:" + port + "/call.action?id=" + id; 

     ResponseEntity<String> response = restTemplate.getForEntity(url, String.class); 

     Assert.assertEquals(HttpStatus.OK, response.getStatusCode()); 

     String body = response.getBody(); 

     // your assertions here 
    } 

} 
+0

洛爾沒有想通這個問題,5年前有人問。無論如何,也許有人覺得這很有用 – 2015-10-30 10:46:30

0

嘗試,因爲你的測試方法!

@Test 
    public void testgetDBRecords(){ 
     MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(wac).build(); 
     mockMvc.perform(get("/call.action?id=id1234").andExpect(status().isOk()) 
    }