Skip to content

Instantly share code, notes, and snippets.

@matsev
Created September 8, 2012 06:13
Show Gist options
  • Save matsev/3672298 to your computer and use it in GitHub Desktop.
Save matsev/3672298 to your computer and use it in GitHub Desktop.
Spring Controller Tests 2.0
@Test
public void shouldGetTestUserAsJson() throws Exception {
mockMvc
.perform(get("/user/0")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("name", is("Test User")))
.andExpect(jsonPath("email", is("test.user@somewhere.com")));
}
@Test
public void shouldGetTestUserAsXml() throws Exception {
mockMvc
.perform(get("/user/0")
.accept(MediaType.APPLICATION_XML))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_XML))
.andExpect(xpath("/user/name").string("Test User"))
.andExpect(xpath("/user/email").string("test.user@somewhere.com"));
}
<repositories>
<repository>
<id>org.springframework.maven.milestone</id>
<name>Spring Framework Maven Milestone Repository</name>
<url>http://maven.springframework.org/milestone</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>3.2.0.RC1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.9.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>0.8.1</version>
<scope>test</scope>
</dependency>
<!-- More dependencies -->
</dependencies>
MockHttpServletRequest:
HTTP Method = GET
Request URI = /user/0
Parameters = {}
Headers = {}
Handler:
Type = com.jayway.controller.UserController
Method = com.jayway.domain.User com.jayway.controller.UserController.getUser(long)
Resolved Exception:
Type = null
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
MockHttpServletResponse:
Status = 200
Error message = null
Headers = {Content-Type=[application/json]}
Content type = application/json
Body = {"name":"Test User","email":"test.user@somewhere.com"}
Forwarded URL = null
Redirected URL = null
Cookies = []
@Test
public void printInfo() throws Exception {
mockMvc
.perform(get("/user/0"))
.andDo(print());
}
@Before
public void setUp() {
userServiceMock = mock(UserService.class);
UserController userController = new UserController(userServiceMock);
testUser = new User("Test User", "test.user@somewhere.com");
when(userServiceMock.getById(0)).thenReturn(testUser);
mockMvc = MockMvcBuilders
.standaloneSetup(userController)
.build();
}
@Test
public void shouldNotPostToUser() throws Exception {
mockMvc
.perform(post("/user/0"))
.andExpect(status().isMethodNotAllowed())
.andExpect(header()
.string("Allow", is("GET")));
}
@XmlRootElement
public class User {
private String name;
private String email;
public User() {
}
public User(String name, String email) {
this.name = name;
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
@Controller
@RequestMapping("/user")
class UserController {
private final UserService userService;
@Autowired
UserController(UserService userService) {
this.userService = userService;
}
@RequestMapping(value = "/{userId}",
method = RequestMethod.GET,
produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE})
@ResponseBody
User getUser(@PathVariable("userId") long userId) {
return userService.getById(userId);
}
}
package com.jayway.controller;
import com.jayway.domain.User;
import com.jayway.service.UserService;
import org.junit.Before;
import org.junit.Test;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import static org.hamcrest.core.Is.is;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
public class UserControllerTest {
UserService userServiceMock;
MockMvc mockMvc;
User testUser;
@Before
public void setUp() {
userServiceMock = mock(UserService.class);
UserController userController = new UserController(userServiceMock);
testUser = new User("Test User", "test.user@somewhere.com");
when(userServiceMock.getById(0)).thenReturn(testUser);
mockMvc = MockMvcBuilders
.standaloneSetup(userController)
.build();
}
@Test
public void shouldGetTestUserAsJson() throws Exception {
mockMvc
.perform(get("/user/0")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("name", is("Test User")))
.andExpect(jsonPath("email", is("test.user@somewhere.com")));
}
@Test
public void shouldGetTestUserAsXml() throws Exception {
mockMvc
.perform(get("/user/0")
.accept(MediaType.APPLICATION_XML))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_XML))
.andExpect(xpath("/user/name").string("Test User"))
.andExpect(xpath("/user/email").string("test.user@somewhere.com"));
}
@Test
public void shouldNotPostToUser() throws Exception {
mockMvc
.perform(post("/user/0"))
.andExpect(status().isMethodNotAllowed())
.andExpect(header()
.string("Allow", is("GET")));
}
@Test
public void printInfo() throws Exception {
mockMvc
.perform(get("/user/0"))
.andDo(print());
}
}
@matsev
Copy link
Author

matsev commented Sep 8, 2012

The purpose of this Gist is to introduce the spring-mvc-test framework. For details, read the blog post at http://www.jayway.com/2012/09/08/spring-controller-tests-2-0/ .

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment