2012-07-25 65 views
1

關於如何使用test-mvc進行單元測試的問題。如何在使用Spring和test-mvc時驗證Web響應

我有一個簡單的控制器:

@Controller 
@RequestMapping("/users") 
public class UserController {   
    private UserService business; 
    @Autowired 
    public UserController(UserService bus) 
    { 
     business = bus; 
    } 
    @RequestMapping(value="{id}", method = RequestMethod.GET) 
    public @ResponseBody User getUserById(@PathVariable String id) throws ItemNotFoundException{ 

     return business.GetUserById(id); 

    } 

((我的想法是,以保持控制器,因此薄越好)。)

爲了測試這個控制器我試圖做這樣的事情。

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(locations = { "classpath:mvc-dispatcher-servlet.xml"}) 
public class UserControllerTest extends ControllerTestBase { 

UserService mockedService; 

@Before 
public void Setup() 
{ 

    MockitoAnnotations.initMocks(this); 
    mockedService = mock(UserService.class); 

} 

@Test 
public void ReturnUserById() throws Exception{ 

    User user = new User(); 
    user.setName("Lasse"); 

    stub(mockedService.GetUserById("lasse")).toReturn(user); 

    MockMvcBuilders.standaloneSetup(new UserController(mockedService)).build() 
    .perform(get("https://stackoverflow.com/users/lasse")) 
    .andExpect(status().isOk()) 
    .andExpect(?????????????????????????????); 

} 

我的目的是檢查返回正確的JSON代碼,,,,,,

我不是更換一個親,,,所以我還沒有找到一種方法????? ??????????????????用代碼來驗證返回的字符串,但我確信必須有一個優雅的方式來做到這一點

任何人都可以填寫我嗎?

// LG

回答

4
content().string(containsString("some part of the string")) 

假設你有這樣導入:

import static org.springframework.test.web.server.result.MockMvcResultMatchers.*; 

更新:添加jsonPath還可根據您的意見:

您可以添加一個依賴於json-path, 1.0.M1似乎取決於json路徑的老版本:

<dependency> 
     <groupId>com.jayway.jsonpath</groupId> 
     <artifactId>json-path</artifactId> 
     <version>0.5.5</version> 
     <scope>test</scope> 
    </dependency> 

有了這個測試可以是這樣的:

.andExpect(jsonPath("$.persons[0].first").value("firstName")); 
+0

好吧,坦克。有一些我試過使用的叫做jsonPath的東西。不過,沒有運氣,瑪比我是完全錯誤的方式? – 2012-07-25 15:19:58

+0

是的,有,我已經添加了一個更新的答案與JSON路徑 – 2012-07-25 16:14:19

+0

再次感謝,這是如此優雅,它可以得到我想:) – 2012-07-27 12:32:02

相關問題