A question about how to use test-mvc for unit testing.
I have a simple controller:
@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);
}
(( My idea is to keep the controllers so thin as possible.))
To test this controller I am trying to do something like this.
@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(?????????????????????????????);
}
My intention is to check that proper json code is returned,,,,,,
I am not a pro,,, so I have not found a way to replace ??????????????????????? with code to do verify the returned string but I am certain that there must be a elegant way to do this
Can anyone fill me in?
//lg
content().string(containsString("some part of the string"))
assuming that you have this import:
import static org.springframework.test.web.server.result.MockMvcResultMatchers.*;
Update: Adding jsonPath also based on your comments:
You can add a dependency to json-path, the 1.0.M1 seems to depend on an much older version of json-path though:
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>0.5.5</version>
<scope>test</scope>
</dependency>
With this your test can look like this:
.andExpect(jsonPath("$.persons[0].first").value("firstName"));