?????????????????????Controller???е???????????????д????????????????????Щ??????н?????????????????????????μ?? (?????)b???????????????????????????????????
?????????????????????
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>1.10.19</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path-assert</artifactId>
<version>0.9.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId>
<version>1.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.0.3.RELEASE</version>
<scope>test</scope>
</dependency>
?????????????Щ??????Spring????????г????
??????????????
????Controller??
@RestController
@RequestMapping("/v0.1/statistics")
public class StatisticsController{
@Autowired
StatisticsService statisticsService;
@RequestMapping(value = "/diaries"?? method = RequestMethod.GET)
public Object getDiariesStatistics(@AuthenticationPrincipal UserInfo userInfo) {
if (userInfo == null) {
throw new BizException(HttpStatus.UNAUTHORIZED?? "UNAUTHORIZED"?? "??????");
}
UserStatistics userStatistics = statisticsService.getDiariesStatistics(userInfo.getUserId());
return entityToVO(userStatistics);
}
}
????Service??
????@Service
????public class StatisticsService {
????@Autowired
????StatisticsRepository statisticsRepository;
????public UserStatistics getDiariesStatistics(String userId) {
????return statisticsRepository.findByUserId(userId);
????}
????}
?????????????Controller???е??????????о?StatisticsRepository??????????????????????о?UserStatistics????????????滻???????塣
??????????Controller???????
????????????????Controller???е?????????????Service????mock???????????????Service??
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import static org.mockito.Matchers.any;
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.*;
public class StatisticsControllerTestWithStandalone {
private MockMvc mockMvc;
@Mock
private StatisticsService statisticsService;
@InjectMocks
private StatisticsController statisticsController;
private UserStatistics userStatistics;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
this.mockMvc = MockMvcBuilders.standaloneSetup(statisticsController).build();
userStatistics = new UserStatistics();
userStatistics.setUserId("330134");
Statistics statistics = new Statistics();
statistics.setDiaryCount(10);
userStatistics.setStatistics(statistics);
}
@Test
public void testGetDiariesStatistics() throws Exception {
when(statisticsService.getDiariesStatistics(any(String.class))).thenReturn(userStatistics);
mockMvc.perform(get("/v0.1/statistics/diaries").header("Authorization"?? "debug userId=330134"))
.andDo(print()).andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("diaryCount").value(10));
verify(statisticsService).getDiariesStatistics(any(String.class));
}
}
????????????′???
????@Mock ??mock?????????
????@InjectMocks ???mock????????????????mock??????????????????У????????StatisticsService???StatisticsController?У???????????StatisticsController????InjectMocks????StatisticsService????mock
????MockitoAnnotations.initMocks(this) ?? ??????Mockito??????????????????Mock????Mock???????Mock????????????Mock?????????
??????? MockMvcBuilders.standaloneSetup ??????Mvc????????????build??????MockMvc
????MockMvc ??????????????????API?????????????????
???????н????
MockHttpServletRequest:
HTTP Method = GET
Request URI = /v0.1/statistics/diaries
Parameters = {}
Headers = {Authorization=[debug userId=330134]}
Handler:
Type = nd.sdp.imdiary.statistics.controller.StatisticsController
Method = public java.lang.Object nd.sdp.imdiary.statistics.controller.StatisticsController.getDiariesStatistics(com.nd.gaea.rest.security.authens.UserInfo)
Async:
Was async started = false
Async result = null
Resolved Exception:
Type = null
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
MockHttpServletResponse:
Status = 200
Error message = null
Headers = {Content-Type=[application/json;charset=UTF-8]}
Content type = application/json;charset=UTF-8
Body = {"diaryCount":10??"firstDiaryDate":null??"lastDiaryDate":null??"unfinishedDate":null}
Forwarded URL = null
Redirected URL = null
Cookies = []
????????????????????????????? any(String.class) ???????????????????Controller????? @AuthenticationPrincipal UserInfo userInfo ??????ò????????????????????μ?Spring Security???н??????????WithSecurityContextTestExcecutionListener??????????????3.2.3?汾??
?????????Web????????
?????е??????????????????м?????????????????????????2?????
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import javax.servlet.Filter;
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.status;
@ContextConfiguration(classes = {WebConfig.class?? MongodbConfig.class})
@WebAppConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
public class StatisticsControllerTest {
protected MockMvc mockMvc;
@Autowired
private Filter springSecurityFilterChain;
@Autowired
private WebApplicationContext wac;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).addFilters(springSecurityFilterChain).build();
}
@After
public void teardown() throws Exception {
SecurityContextHolder.clearContext();
}
@Test
public void testGetDiariesStatistics() throws Exception {
mockMvc.perform(get("/v0.1/statistics/diaries").header("Authorization"?? "debug userId=330134"))
.andDo(print()).andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON));
}
}
????????????????????????????????Щ??????????????????????????????????????Service??mock??????????mockmvc????????????
????@ContextConfiguration() ?????Bean??????????????????????????????????WebConfig.class?????????????xml?????????????滻??????xml????
????@WebAppConfiguration ???????е?????????????????Web???????е??????????????????
????@RunWith(SpringJUnit4ClassRunner.class) ??????Spring Test??????е??????
????@Autowired WebApplicationContext wac ?????web??????ApplicationContext????
????MockMvcBuilders.webAppContextSetup(this.wac) ??????????Spring MVC????
????@Autowired Filter springSecurityFilterChain ?????SecurityContextPersistenceFilter