Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save qsLI/3ad39c82972ed66de3d5934f1cdcedaa to your computer and use it in GitHub Desktop.
Save qsLI/3ad39c82972ed66de3d5934f1cdcedaa to your computer and use it in GitHub Desktop.
使用Mockito测试Spring MVC 的Controller
package sample.uic.web.controller;
import sample.uic.model.Organization;
import sample.uic.model.OrganizationUser;
import sample.uic.model.User;
import sample.uic.service.OrganizationService;
import sample.uic.service.UserService;
import com.google.common.collect.Lists;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import java.util.ArrayList;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
/**
* Created by yanhua on 14-3-9.
*/
@RunWith(MockitoJUnitRunner.class)
public class OrgAndUserSelectionControllerTest {
private MockMvc mockMvc;
@InjectMocks
private OrgAndUserSelectionController controller;
@Mock
private OrganizationService orgService;
@Mock
private UserService userService;
private User user1;
private User user2;
private Organization org1;
private Organization org11;
private Organization org12;
private Organization org121;
private Organization org122;
@Before
public void setUp() {
mockMvc = MockMvcBuilders.standaloneSetup(controller)
.setMessageConverters(new MappingJackson2HttpMessageConverter())
.build();
org1 = new Organization();
org1.setId(1L);
org1.setType(6);
org1.setName("学校");
org1.setParentId(null);
org11 = new Organization();
org11.setId(11L);
org11.setType(6);
org11.setName("校办");
org11.setParentId(1L);
org12 = new Organization();
org12.setId(12L);
org12.setType(1);
org12.setName("学生办");
org12.setParentId(1L);
org121 = new Organization();
org121.setId(121L);
org121.setType(6);
org121.setName("学生会");
org121.setParentId(12L); user1 = new User();
org122 = new Organization();
org122.setId(122L);
org122.setType(6);
org122.setName("医务部");
org122.setParentId(12L);
user1 = new User();
user1.setId(1L);
user1.setUsername("Tom");
user1.setFullname("Tom");
user2 = new User();
user2.setId(1L);
user2.setUsername("Tony");
user2.setFullname("Tony");
OrganizationUser ou1 = new OrganizationUser();
ou1.setUser(user1);
ou1.setOrganization(org121);
OrganizationUser ou2 = new OrganizationUser();
ou2.setUser(user1);
ou2.setOrganization(org122);
user1.getOrganizationUsers().add(ou1);
user1.getOrganizationUsers().add(ou2);
}
@Test
public void thatOrgsFindByTypeRendersAsJson() throws Exception{
ArrayList<Organization> organizations = Lists.newArrayList(org1, org11, org12, org121, org122);
when(orgService.findOrgsByCategory(eq(6)))
.thenReturn(organizations);
mockMvc.perform(get("/uic/orgs/user-type/6")
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andDo(print())
.andExpect(status().isOk())
.andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$", hasSize(5)))
.andExpect(jsonPath("$[0].id", is(1)))
.andExpect(jsonPath("$[0].name", is("学校")))
.andExpect(jsonPath("$[0].parentId", is(nullValue())))
.andExpect(jsonPath("$[1].id", is(11)))
.andExpect(jsonPath("$[1].name", is("校办")))
.andExpect(jsonPath("$[1].parentId", is(1)))
.andExpect(jsonPath("$[2].id", is(12)))
.andExpect(jsonPath("$[2].name", is("学生办")))
.andExpect(jsonPath("$[2].parentId", is(1)));
verify(orgService, times(1)).findOrgsByCategory(eq(6));
}
@Test
public void thatUsersFindByOrgIdRendersAsJson() throws Exception{
when(userService.findValidUsersByOrgWithOrgs(eq(1L)))
.thenReturn(Lists.newArrayList(user1, user2));
mockMvc.perform(get("/uic/users/org/1")
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andDo(print())
.andExpect(status().isOk())
.andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$",hasSize(2)))
.andExpect(jsonPath("$[0].userName",is("Tom")))
.andExpect(jsonPath("$[1].userName",is("Tony")));
//.andExpect(jsonPath("$[0].orgs",hasSize(2)))
//.andExpect(jsonPath("$[0].orgs[0].name",is("学生会")))
//.andExpect(jsonPath("$[0].orgs[1].name", is("医务部")));
verify(userService, times(1)).findValidUsersByOrgWithOrgs(eq(1L));
}
@Test
public void thatUsersFindBySearchRendersAsJson() throws Exception{
ArrayList<Integer> types = Lists.newArrayList(1, 2);
when(userService.findValidUsersByCategoriesAndSearchWithOrgs( eq(types), eq("To")))
.thenReturn(Lists.newArrayList(user1, user2));
mockMvc.perform(get("/uic/users/search?q=To&types=1,2")
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andDo(print())
.andExpect(status().isOk())
.andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$",hasSize(2)))
.andExpect(jsonPath("$[0].userName",is("Tom")))
.andExpect(jsonPath("$[1].userName", is("Tony")));
verify(userService, times(1)).findValidUsersByCategoriesAndSearchWithOrgs( eq(types), eq("To") );
}
@Test
public void thatUserFindByIdRendersAsJson() throws Exception{
//TODO 通过ID得到用户,且用户有组织信息
}
}
package sample.uic.rest.controller;
import sample.base.client.BasePlatformInvoker;
import sample.uic.model.User;
import sample.uic.service.TcSyncToUcService;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
/**
* Created by yanhua on 14-4-11.
*/
@RunWith(MockitoJUnitRunner.class)
public class TcSyncToUcApiControllerTest {
public static final String CORRECT_APP_ID = "correctAppId";
public static final String CORRECT_TOKEN = "correctPassword";
private MockMvc mockMvc;
@InjectMocks
TcSyncToUcApiController controller;
@Mock
private TcSyncToUcService service;
@Mock
BasePlatformInvoker basePlatformInvoker;
private User user1;
@Before
public void setUp() {
mockMvc = MockMvcBuilders.standaloneSetup(controller)
.setMessageConverters(new MappingJackson2HttpMessageConverter())
.build();
user1 = new User();
user1.setId(1L);
user1.setUsername("user1");
}
@Test
public void thatUpdateGradeNameCorrectly() throws Exception{
when(basePlatformInvoker.validateToken(anyString(), anyString(), anyString())).thenReturn(true);
mockMvc.perform(post("/api/uic/tc-sync/grade/update-grade-name")
.header("appKey", CORRECT_APP_ID)
.header("token", CORRECT_TOKEN)
.param("grade-id", "a_exists_grade_source_id")
.param("grade-name", "wang")
)
.andDo(print())
.andExpect(status().isOk())
verify(service, times(1)).updateGradeName(eq("a_exists_grade_source_id"),eq("wang"));
verify(basePlatformInvoker,times(1)).validateToken(anyString(), anyString(), anyString());
}
@Test
public void thatUpdateGradeNameWithErrorGradeSourceId() throws Exception{
when(basePlatformInvoker.validateToken(anyString(), anyString(), anyString())).thenReturn(true);
doThrow(new TcSyncToUcService.GradeNotExistsException()).when(service).updateGradeName(eq("a_not_exists_grade_source_id"),eq("wang"));
mockMvc.perform(post("/api/uic/tc-sync/grade/update-grade-name")
.header("appKey",CORRECT_APP_ID)
.header("token", CORRECT_TOKEN)
.param("grade-id", "a_not_exists_grade_source_id")
.param("grade-name", "wang")
)
.andDo(print())
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.code").value(101));
verify(service, times(1)).updateGradeName(eq("a_not_exists_grade_source_id"),eq("wang"));
verify(basePlatformInvoker,times(1)).validateToken(anyString(), anyString(), anyString());
}
}
package sample.uic.rest.controller;
import sample.base.remote.rest.BasePlatformService;
import sample.uic.model.User;
import sample.uic.service.UserService;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
/**
* Created by yanhua on 14-3-3.
*/
@RunWith(MockitoJUnitRunner.class)
public class UserApiControllerTest {
public static final String CORRECT_APP_ID = "correctAppId";
public static final String CORRECT_TOKEN = "correctPassword";
private MockMvc mockMvc;
@InjectMocks
UserApiController controller;
@Mock
private UserService userService;
@Mock
BasePlatformService basePlatformService;
private User user1;
@Before
public void setUp() {
mockMvc = MockMvcBuilders.standaloneSetup(controller)
.setMessageConverters(new MappingJackson2HttpMessageConverter())
.build();
user1 = new User();
user1.setId(1L);
user1.setUsername("user1");
}
@Test
public void thatUserRendersAsJson() throws Exception{
when(userService.findUserByIdWithOrgs(eq(1L)))
.thenReturn(user1);
when(basePlatformService.validateToken(anyString(), anyString(), anyString())).thenReturn(true);
mockMvc.perform(get("/api/uic/user/1")
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)
.header("User-Agent", "MockTest")
.header("Cache-Control", "no-cache")
.header("appKey",CORRECT_APP_ID)
.header("token", CORRECT_TOKEN))
.andDo(print())
.andExpect(status().isOk())
.andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$.id").value(1))
.andExpect(jsonPath("$.userName").value("user1"));
verify(userService, times(1)).findUserByIdWithOrgs(eq(1L));
verify(basePlatformService,times(1)).validateToken(anyString(), anyString(), anyString());
}
@Test
public void thatUserCannotOperatedWithBadAppIdOrToken() throws Exception {
String errorToken = "a_error_token";
when(basePlatformService.getCurrentAppKey()).thenReturn("BASE");
when(basePlatformService.validateToken(anyString(), anyString(), anyString())).thenReturn(false);
mockMvc.perform(get("/api/uic/user/1")
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)
.header("User-Agent", "MockTest")
.header("Cache-Control", "no-cache")
.header("appKey",CORRECT_APP_ID)
.header("token", errorToken))
.andDo(print())
.andExpect(status().isUnauthorized());
verify(basePlatformService,times(1)).validateToken(anyString(), anyString(), anyString());
verify(basePlatformService,times(1)).getCurrentAppKey();
}
}
@qsLI
Copy link
Author

qsLI commented Sep 19, 2016

thank you for sharing

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