문제

단위 테스트를 위해 Test-MVC를 사용하는 방법에 대한 질문입니다.

단순 컨트롤러가 있습니다.

@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("/users/lasse"))
    .andExpect(status().isOk())
    .andExpect(?????????????????????????????);

}
.

적절한 JSON 코드가 반환되는지 확인하는 것입니다 .,,,,,

나는 프로가 아닙니다. 그래서 나는 교체하는 방법을 찾지 못했습니다 ???????????????????????????????????????????????????????????????????????????????????????????????????????????????????반환 된 문자열을 확인하기 위해 코드가 있지만이 작업을 수행 할 수있는 우아한 방법이 있어야합니다

누구든지 나를 채울 수 있습니까?

// lg

도움이 되었습니까?

해결책

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

이 가져 오기가 있다고 가정합니다.

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

업데이트 : 주석을 기반으로 JSONPATH 추가 :

json-path 에 종속성을 추가 할 수 있습니다. 1.0.m1JSON-PATH의 훨씬 오래된 버전에 의존하는 것 :

    <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"));
.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top