@Test public void testPage() throws Exception{ //模拟请求拿到返回值 MvcResult result = movkMVC.perform(MockMvcRequestBuilders.get("/emps").param("pn", "3")).andReturn(); //请求成功以后,请求域中会有pageInfo:我们可以取出pageinfo进行验证 MockHttpServletRequest request = result.getRequest(); PageInfo pi = (PageInfo)request.getAttribute("PageInfo"); System.out.println("当前页码:"+pi.getPageNum()); System.out.println("总页码:"+pi.getPages()); System.out.println("总记录数:"+pi.getTotal()); System.out.println("在页面需要连续显示的页码"); int[] nums= pi.getNavigatepageNums(); for(int i:nums){ System.out.println(" "+i); } //获取员工数据 List<Employee> list= pi.getList(); for(Employee employee : list ){ System.out.println("ID:" +employee.getEmpId()+"==>Name:"+employee.getEmpName()); } }
@Test public void testAddBook_Form_validation() { try { mockMVC.perform(MockMvcRequestBuilders.post("/addBook.htm") .contentType(MediaType.APPLICATION_FORM_URLENCODED) .param("bookName", "Book_test") .param("author", "author_test") .param("description", "adding book for test") .param("ISBN", "1234") .param("price", "9191") .param("publication", "This is the test publication") .requestAttr("book", new Book())) .andExpect(MockMvcResultMatchers.view().name("bookForm")) .andExpect( MockMvcResultMatchers .model() .attributeHasErrors("book")) .andDo(MockMvcResultHandlers.print()); } catch (Exception e) { // TODO: handle exception fail(e.getMessage()); e.printStackTrace(); } }
@Test public void should_get_the_preset_shop_list() throws Exception { MvcResult mvcResult = this.mockMvc.perform(MockMvcRequestBuilders.get("/api/shops") .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andReturn(); List<ShopResponse> shops = this.objectMapper.readValue( mvcResult.getResponse().getContentAsByteArray(), new TypeReference<List<ShopResponse>>(){}); assertEquals(1, shops.size()); ShopResponse shop = shops.get(0); assertEquals(shopName, shop.getName()); }
@Test public void testProcessSingleRadioMapFile() { try { long buildingId = TestHelper.addNewBuildingAndRetrieveId(this.mockMvc, this.contentType); assertTrue("Failed to add new building.", buildingId > 0); mockMvc.perform(MockMvcRequestBuilders.fileUpload("/position/processRadioMapFiles") .file(radioMapFileR01A5) .param("buildingIdentifier", String.valueOf(buildingId))) .andExpect(status().isOk()); } catch (Exception e) { e.printStackTrace(); fail("An unexpected Exception of type " + e.getClass().getSimpleName() + " has occurred."); } }
@Test public void testProcessEmptyRadioMapFile() { try { long buildingId = TestHelper.addNewBuildingAndRetrieveId(this.mockMvc, this.contentType); assertTrue("Failed to add new building.", buildingId > 0); mockMvc.perform(MockMvcRequestBuilders.fileUpload("/position/processRadioMapFiles") .file(emptyRadioMapFileHfT) .file(transformedPointsFile) .param("buildingIdentifier", String.valueOf(buildingId))) .andExpect(status().isOk()); } catch (Exception e) { e.printStackTrace(); fail("An unexpected Exception of type " + e.getClass().getSimpleName() + " has occurred."); } }
private long processEvaluationFileForBuilding(long buildingId) throws Exception { mockMvc.perform(MockMvcRequestBuilders.fileUpload("/position/processEvalFiles") .file(evaluationFile) .param("buildingIdentifier", String.valueOf(buildingId))) .andExpect(status().isOk()); ResultActions getEvalFileResultActions = mockMvc.perform(get("/position/getEvalFilesForBuildingId?" + "buildingIdentifier=" + buildingId)); getEvalFileResultActions.andExpect(status().isOk()); String getEvalFileResult = getEvalFileResultActions.andReturn().getResponse().getContentAsString(); List<GetEvaluationFilesForBuilding> getEvaluationFilesForBuilding = (List<GetEvaluationFilesForBuilding>) this.objectMapper.readValue(getEvalFileResult, new TypeReference<List<GetEvaluationFilesForBuilding>>() { }); assertTrue("The returned list of type " + GetEvaluationFilesForBuilding.class.getSimpleName() + " had an unexpected size.", getEvaluationFilesForBuilding.size() == 1); return getEvaluationFilesForBuilding.get(0).getId(); }
@Test public void testUpdatePassword() throws Exception { User user = UserFixture.buildPersistentUser(); when(userRepository.findOne(2L)) .thenReturn(user); mvc.perform(MockMvcRequestBuilders.put("/user/{userId}/change-password", 2L).content(PASSWORD_JSON) .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON)).andExpect(status().isAccepted()); user.setPassword("ZYX"); verify(userRepository, times(1)) .save(user); }
public ResultActions postDocument(String urlTemplate, MultipartFile file) { return translateException(() -> mvc.perform( MockMvcRequestBuilders.fileUpload(urlTemplate).file((MockMultipartFile)file) .headers(httpHeaders) )); }
public ResultActions postDocumentVersion(String urlTemplate, MockMultipartFile file) { MockMultipartHttpServletRequestBuilder builder = MockMvcRequestBuilders.fileUpload(urlTemplate); builder.with(request -> { request.setMethod("POST"); return request; }); return translateException(() -> mvc.perform( builder .file(file) .headers(httpHeaders) )); }
@Test public void test() throws Exception { mockUtil.requestContextExecutor().execute(new Executable() { @Override public void execute() throws Exception { mvc.perform(MockMvcRequestBuilders.get("/hello")) .andExpect(status().isOk()) .andExpect(content().json( IOUtils.toString( currentThread().getContextClassLoader().getResourceAsStream("expected.json")))); } }); }
@Test public void testHttpGet() throws Exception { mockSdk.requestContextExecutor().execute(new Executable() { @Override public void execute() throws Exception { ResultActions action = mockMvc.perform(MockMvcRequestBuilders .put("/callback/tenant/" + TENANT_ID_1)); action.andExpect(MockMvcResultMatchers.status().is2xxSuccessful()); action = mockMvc.perform(MockMvcRequestBuilders .get("/cost-center")); action.andExpect(MockMvcResultMatchers.status().isOk()); action = mockMvc.perform(MockMvcRequestBuilders .delete("/callback/tenant/" + TENANT_ID_1)); action.andExpect(MockMvcResultMatchers.status().is2xxSuccessful()); } }); }
@Test public void testHttpPost() throws Exception { final String newCostCenterJson = buildCostCenterJson(COSTCENTER_ID_1); mockSdk.requestContextExecutor().execute(new Executable() { @Override public void execute() throws Exception { ResultActions action = mockMvc.perform(MockMvcRequestBuilders .put("/callback/tenant/" + TENANT_ID_1)); action.andExpect(MockMvcResultMatchers.status().is2xxSuccessful()); action = mockMvc .perform(MockMvcRequestBuilders .request(HttpMethod.POST, "/cost-center") .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON) .content(newCostCenterJson)); action.andExpect(MockMvcResultMatchers.status().isOk()); action = mockMvc.perform(MockMvcRequestBuilders .delete("/callback/tenant/" + TENANT_ID_1)); action.andExpect(MockMvcResultMatchers.status().is2xxSuccessful()); } }); }
@Test public void testAddBook() { try { mockMVC.perform(MockMvcRequestBuilders.post("/addBook.htm") .contentType(MediaType.APPLICATION_FORM_URLENCODED) .param("bookName", "Book_test") .param("author", "author_test") .param("description", "adding book for test") .param("ISBN", "1234") .param("price", "9191") .param("publication", "This is the test publication") .requestAttr("book", new Book())) .andExpect(MockMvcResultMatchers.view().name("display")) .andExpect(MockMvcResultMatchers.model().attribute("auth_name","author_test")) .andDo(MockMvcResultHandlers.print()); ; } catch (Exception e) { // TODO: handle exception fail(e.getMessage()); } }
@Test public void checkApplicationInfoTest() throws Exception { RequestBuilder requestBuilder = MockMvcRequestBuilders.get("/info").contentType(MediaType.ALL) .accept(MediaType.ALL); mvc.perform(requestBuilder).andExpect(MockMvcResultMatchers.status().isOk()); }
@Test public void getCustomerByIdShouldReturnCustomer() throws Exception { Mockito .when(this.customerRepository.findOne(1L)) .thenReturn(c1); mockMvc.perform(MockMvcRequestBuilders.get("/customers/1")) .andExpect(MockMvcResultMatchers.status().is2xxSuccessful()) .andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(MockMvcResultMatchers.jsonPath("@.id").value(1L)) .andDo(MockMvcRestDocumentation.document("customerById")); }
@Test public void getCustomersShouldReturnAllCustomers() throws Exception { Mockito .when(this.customerRepository.findAll()) .thenReturn(Arrays.asList(c1, c2)); mockMvc.perform(MockMvcRequestBuilders.get("/customers")) .andExpect(MockMvcResultMatchers.jsonPath("@.[0].id").value(1L)) .andExpect(MockMvcResultMatchers.jsonPath("@.[0].first").value("first")) .andExpect(MockMvcResultMatchers.status().is2xxSuccessful()) .andDo(document("customers")); }
@Test public void shouldBeHealthy() throws Exception { mockMvc.perform(MockMvcRequestBuilders.request(HttpMethod.GET, "/health")) .andExpect(status().is(200)) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) .andExpect(jsonPath("$.environmentVariables").exists()) .andExpect(jsonPath("$.systemProperties").exists()) .andExpect(jsonPath("$.implementationVersion").exists()); }
@Test public void checkMetricsTest() throws Exception { RequestBuilder requestBuilder = MockMvcRequestBuilders.get("/metrics").contentType(MediaType.ALL) .accept(MediaType.ALL); mvc.perform(requestBuilder).andExpect(MockMvcResultMatchers.status().isOk()); }
@Test(dataProvider = "urisAndTheirAllowedHttpMethods") public void testUriPatternsAndTheirAllowedHttpMethods(final String uri, final Set<HttpMethod> allowedHttpMethods) throws Exception { Set<HttpMethod> disallowedHttpMethods = new HashSet<>(ALL_HTTP_METHODS); disallowedHttpMethods.removeAll(allowedHttpMethods); for (HttpMethod disallowedHttpMethod : disallowedHttpMethods) { this.mockMvc.perform(MockMvcRequestBuilders.request(disallowedHttpMethod, URI.create(uri))) .andExpect(MockMvcResultMatchers.status().isMethodNotAllowed()); } }
@Test public void testInvalidQpp() throws Exception { MockMultipartFile qrda3File = new MockMultipartFile("file", Files.newInputStream(Paths.get("../qrda-files/not-a-QDRA-III-file.xml"))); mockMvc.perform(MockMvcRequestBuilders .fileUpload("/").file(qrda3File)) .andExpect(status().is(422)) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) .andExpect(jsonPath("$.errors").exists()); }
@Test public void testInvalidAcceptHeader() throws Exception { MockMultipartFile qrda3File = new MockMultipartFile("file", Files.newInputStream(Paths.get("../qrda-files/not-a-QDRA-III-file.xml"))); mockMvc.perform(MockMvcRequestBuilders .fileUpload("/").file(qrda3File) .accept("application/vnd.qpp.cms.gov.v2+json")) .andExpect(status().is(406)); }
@Test public void shouldFailForSubmissionApiValidation() throws Exception { String file = "../rest-api/src/test/resources/fail_validation.xml"; MockMultipartFile qrda3File = new MockMultipartFile("file", Files.newInputStream(Paths.get(file))); mockMvc.perform(MockMvcRequestBuilders .fileUpload("/").file(qrda3File)) .andExpect(status().is(422)) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) .andExpect(jsonPath("$.errors[0].type").value("ValidationError")); }
@Test public void findAll() throws Exception { mvc.perform(MockMvcRequestBuilders.get("/wowtokens")) .andExpect(MockMvcResultMatchers.status().isOk()) // .andExpect(MockMvcResultMatchers.content().string("abc")); // 判断返回的内容 ; }
@Test public void testIncorrectJwtGetCpcFile() throws Exception { JwtPayloadHelper jwtPayload = new JwtPayloadHelper().withName(NOT_CPC).withOrgType(ORG_TYPE); mockMvc.perform(MockMvcRequestBuilders .get("/cpc/file/uuid").header("Authorization", JwtTestHelper.createJwt(jwtPayload))) .andExpect(status().is(403)); }
@Test public void testSave() throws Exception { //创建书架创建的请求 //请求方式为post MockHttpServletRequestBuilder mockHttpServletRequestBuilder = MockMvcRequestBuilders.post("/store/save.do"); //添加编号为MockMvc的书架 mockHttpServletRequestBuilder.param("number", "MockMvc"); //书架为两层 mockHttpServletRequestBuilder.param("level", "2"); mockMvc.perform(mockHttpServletRequestBuilder).andExpect(status().isOk()) .andDo(print()); }
@Test public void testGetStockEntries() throws Exception { when(stockService.quantityOfAvailableProducts(1l)).thenReturn(StockFixture.buildQuantityOfAvailableProducts()); mvc.perform(MockMvcRequestBuilders.get("/stock/{stockId}/entries", 1l) .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().json("[{\"productId\":1,\"quantity\":24},{\"productId\":2,\"quantity\":12},{\"productId\":3,\"quantity\":6}]")); verify(stockService, times(1)).quantityOfAvailableProducts(1l); }
@Test public void testUpdateProduct() throws Exception { when(productRepository.findOne(1L)).thenReturn(buildPersistentProduct()); mvc.perform(MockMvcRequestBuilders.put("/product/{productId}", 1L) .contentType(MediaType.APPLICATION_JSON) .content(PRODUCT_JSON) .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()); verify(productRepository, times(1)).save(any(Product.class)); }
@Test public void registerTest() throws Exception { Map<String, Object> data = new HashMap<>(); data.put("email", System.currentTimeMillis()+"@126.com"); data.put("password", "123456"); data.put("nickname", System.currentTimeMillis()+"-TESTER"); mockMvc.perform(MockMvcRequestBuilders .post("/register") .contentType(MediaType.APPLICATION_JSON_UTF8) .content(JSON.toJSONString(data)) ).andExpect(MockMvcResultMatchers.status().isOk()); }
@Test @WithMockUser public void testCadastrarLancamentoFuncionarioIdInvalido() throws Exception { BDDMockito.given(this.funcionarioService.buscarPorId(Mockito.anyLong())).willReturn(Optional.empty()); mvc.perform(MockMvcRequestBuilders.post(URL_BASE) .content(this.obterJsonRequisicaoPost()) .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isBadRequest()) .andExpect(jsonPath("$.errors").value("Funcionário não encontrado. ID inexistente.")) .andExpect(jsonPath("$.data").isEmpty()); }
@Test public void testAddFloorMapGif(){ try { long buildingId = TestHelper.addNewBuildingAndRetrieveId(this.mockMvc, this.contentType); assertTrue("Failed to add new building.", buildingId > 0); ResultActions getBuildingActions = mockMvc.perform(get("/building/getBuildingByBuildingId?" + "buildingIdentifier=" + buildingId)); getBuildingActions.andExpect(status().isOk()); String result = getBuildingActions.andReturn().getResponse().getContentAsString(); GetSingleBuilding getSingleBuilding = this.objectMapper.readValue(result, GetSingleBuilding.class); String floorName = "SomeFloor"; mockMvc.perform(MockMvcRequestBuilders .fileUpload("/building/addFloorToBuilding") .file(floorMapGif) .param("buildingIdentifier", String.valueOf(getSingleBuilding.getBuildingId())) .param("floorIdentifier", String.valueOf(getSingleBuilding.getBuildingFloors().get(0).getFloorId())) .param("floorName", floorName)) .andExpect(status().isOk()); mockMvc.perform(get("/building/getBuildingByBuildingId?" + "buildingIdentifier=" + buildingId)) .andExpect(status().isOk()) .andExpect(jsonPath("$.buildingFloors[0].floorMapUrl", is("building/getFloorMap?floorIdentifier=" + buildingId))); } catch (Exception e) { e.printStackTrace(); fail("An unexpected Exception of type " + e.getClass().getSimpleName() + " has occurred."); } }
@Test public void testAddFloorMapJpg(){ try { long buildingId = TestHelper.addNewBuildingAndRetrieveId(this.mockMvc, this.contentType); assertTrue("Failed to add new building.", buildingId > 0); ResultActions getBuildingActions = mockMvc.perform(get("/building/getBuildingByBuildingId?" + "buildingIdentifier=" + buildingId)); getBuildingActions.andExpect(status().isOk()); String result = getBuildingActions.andReturn().getResponse().getContentAsString(); GetSingleBuilding getSingleBuilding = this.objectMapper.readValue(result, GetSingleBuilding.class); String floorName = "SomeFloor"; mockMvc.perform(MockMvcRequestBuilders .fileUpload("/building/addFloorToBuilding") .file(floorMapJpg) .param("buildingIdentifier", String.valueOf(getSingleBuilding.getBuildingId())) .param("floorIdentifier", String.valueOf(getSingleBuilding.getBuildingFloors().get(0).getFloorId())) .param("floorName", floorName)) .andExpect(status().isOk()); mockMvc.perform(get("/building/getBuildingByBuildingId?" + "buildingIdentifier=" + buildingId)) .andExpect(status().isOk()) .andExpect(jsonPath("$.buildingFloors[0].floorMapUrl", is("building/getFloorMap?floorIdentifier=" + buildingId))); } catch (Exception e) { e.printStackTrace(); fail("An unexpected Exception of type " + e.getClass().getSimpleName() + " has occurred."); } }
@Test public void testProcessMultipleRadioMapFiles() { try { long buildingId = TestHelper.addNewBuildingAndRetrieveId(this.mockMvc, this.contentType); assertTrue("Failed to add new building.", buildingId > 0); mockMvc.perform(MockMvcRequestBuilders.fileUpload("/position/processRadioMapFiles") .file(radioMapFileR01A5) .file(radioMapFileR01S4Mini) .file(radioMapFileR01S4) .file(radioMapFileR02A5) .file(radioMapFileR02S4Mini) .file(radioMapFileR02S4) .file(radioMapFileR03S4Mini) .file(radioMapFileR03S4) .file(radioMapFileR04A5) .file(radioMapFileR04S4Mini) .file(radioMapFileR04S4) .param("buildingIdentifier", String.valueOf(buildingId))) .andExpect(status().isOk()); } catch (Exception e) { e.printStackTrace(); fail("An unexpected Exception of type " + e.getClass().getSimpleName() + " has occurred."); } }
@Test public void retrieveTodos() throws Exception { List<Todo> mockList = Arrays.asList(new Todo(1, "Jack", "Learn Spring MVC", new Date(), false), new Todo(2, "Jack", "Learn Struts", new Date(), false)); when(service.retrieveTodos(anyString())).thenReturn(mockList); MvcResult result = mvc .perform(MockMvcRequestBuilders.get("/users/Jack/todos").accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()).andReturn(); String expected = "[" + "{id:1,user:Jack,desc:\"Learn Spring MVC\",done:false}" + "," + "{id:2,user:Jack,desc:\"Learn Struts\",done:false}" + "]"; JSONAssert.assertEquals(expected, result.getResponse().getContentAsString(), false); }
@Test public void helloLucaTest() throws Exception { mockMvc.perform(MockMvcRequestBuilders.get("/hello/Luca").accept(MediaType.TEXT_PLAIN)) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.view().name("greeting")) .andExpect(MockMvcResultMatchers.model().attributeExists("name")) .andExpect(MockMvcResultMatchers.model().attribute("name", "Luca")) .andExpect(MockMvcResultMatchers.content().string(containsString("Hello, <span>Luca</span>!"))); }