org.springframework.test.web.servlet.request.MockMvcRequestBuilders Java Examples

The following examples show how to use org.springframework.test.web.servlet.request.MockMvcRequestBuilders. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TransControllerTest.java    From WeBASE-Front with Apache License 2.0 7 votes vote down vote up
@Test
public void testDeploy() throws Exception {
    //test new
    ReqSignedTransHandle testNew = new ReqSignedTransHandle();
    testNew.setGroupId(groupId);
    testNew.setSignedStr("0xf904faa0029773c124ce6901ed2f209201d86cf5e46b855859ffff79456d7cc0096fbb4385051f4d5c0083419ce082aecb8080b90481608060405234801561001057600080fd5b5060016000800160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506402540be40060006001018190555060028060000160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555060006002600101819055506103bf806100c26000396000f30060806040526004361061004c576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff16806366c99139146100515780636d4ce63c1461007e575b600080fd5b34801561005d57600080fd5b5061007c600480360381019080803590602001909291905050506100a9565b005b34801561008a57600080fd5b506100936102e1565b6040518082815260200191505060405180910390f35b8060006001015410806100c757506002600101548160026001015401105b156100d1576102de565b8060006001015403600060010181905550806002600101600082825401925050819055507fc77b710b83d1dc3f3fafeccd08a6c469beb873b2f0975b50d1698e46b3ee5b4c816040518082815260200191505060405180910390a160046080604051908101604052806040805190810160405280600881526020017f323031373034313300000000000000000000000000000000000000000000000081525081526020016000800160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001600260000160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001838152509080600181540180825580915050906001820390600052602060002090600402016000909192909190915060008201518160000190805190602001906102419291906102ee565b5060208201518160010160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555060408201518160020160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550606082015181600301555050505b50565b6000600260010154905090565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f1061032f57805160ff191683800117855561035d565b8280016001018555821561035d579182015b8281111561035c578251825591602001919060010190610341565b5b50905061036a919061036e565b5090565b61039091905b8082111561038c576000816000905550600101610374565b5090565b905600a165627a7a7230582047862dd7accfd1db3db5acd78a1024d17dcfe40e8181e4a11bfb1f31d2a0f84400290101801ba027aa21cdb788f99fd59a0ac1e10b173a9c972299bae9a1d93db17aa02ebfd836a01ec63c211c93814629f987144be7bba5232fcac7411c9779658bd9fc2a966c96");
    testNew.setSync(Boolean.TRUE);

    ResultActions resultActions = mockMvc.perform(MockMvcRequestBuilders.post("/trans/signed-transaction").
        content(JsonUtils.toJSONString(testNew)).
        contentType(MediaType.APPLICATION_JSON)
    );
    resultActions.
        andExpect(MockMvcResultMatchers.status().isOk()).
        andDo(MockMvcResultHandlers.print());
    System.out
        .println("response:" + resultActions.andReturn().getResponse().getContentAsString());
}
 
Example #2
Source File: TestPointController.java    From hyena with Apache License 2.0 6 votes vote down vote up
@Test
public void test_listPoint() throws Exception {

    ListPointParam param = new ListPointParam();
    param.setType(super.getPointType());
    param.setUidList(List.of(super.getUid()));
    param.setStart(0L).setSize(10);


    RequestBuilder builder = MockMvcRequestBuilders.post("/hyena/point/listPoint")
            .contentType(MediaType.APPLICATION_JSON)
            .content(JsonUtils.toJsonString(param));

    String resBody = mockMvc.perform(builder).andReturn().getResponse().getContentAsString();
    logger.info("response = {}", resBody);
    ListResponse<PointPo> res = JsonUtils.fromJson(resBody, new TypeReference<ListResponse<PointPo>>() {

    });
    List<PointPo> list = res.getData();
    Assertions.assertFalse(list.isEmpty());
}
 
Example #3
Source File: Web3ApiControllerTest.java    From WeBASE-Front with Apache License 2.0 6 votes vote down vote up
@Test
public void testGroupStatusList() throws Exception {
    ReqGroupStatus param = new ReqGroupStatus();
    List<Integer> groupIdList = new ArrayList<>();
    groupIdList.add(2020);
    groupIdList.add(3);
    groupIdList.add(1);
    groupIdList.add(2021);
    groupIdList.add(2023);
    param.setGroupIdList(groupIdList);
    ResultActions resultActions = mockMvc.perform(MockMvcRequestBuilders
            .post("/3/web3/queryGroupStatus")
            .content(JsonUtils.toJSONString(param))
            .contentType(MediaType.APPLICATION_JSON_UTF8)
    );
    resultActions.
            andExpect(MockMvcResultMatchers.status().isOk()).
            andDo(MockMvcResultHandlers.print());
    System.out.println("=================================response:"+resultActions.andReturn().getResponse().getContentAsString());
}
 
Example #4
Source File: GridDatasetControllerTest.java    From tds with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void getGridSubsetOnGridDatasetNc4() throws Exception {
  RequestBuilder rb = MockMvcRequestBuilders.get("/ncss/grid/testGFSfmrc/GFS_CONUS_80km_nc_best.ncd")
      .servletPath("/ncss/grid/testGFSfmrc/GFS_CONUS_80km_nc_best.ncd")
      .param("accept", SupportedFormat.NETCDF4.getFormatName())
      .param("var", "Relative_humidity_height_above_ground", "Temperature_height_above_ground");

  MvcResult result = this.mockMvc.perform(rb).andExpect(MockMvcResultMatchers.status().isOk())
      .andExpect(MockMvcResultMatchers.content().contentType(SupportedFormat.NETCDF4.getMimeType()))
      .andExpect(MockMvcResultMatchers.header().string(Constants.Content_Disposition, new FilenameMatcher(".nc4")))
      .andReturn();

  System.out.printf("Headers%n");
  for (String name : result.getResponse().getHeaderNames()) {
    System.out.printf("%s= %s%n", name, result.getResponse().getHeader(name));
  }
}
 
Example #5
Source File: TestSystemController.java    From hyena with Apache License 2.0 6 votes vote down vote up
@Test
public void test_dumpMemCache() throws Exception {
    String pointType = UUID.randomUUID().toString().replace("-", "").substring(0, 10);
    RequestBuilder builder = MockMvcRequestBuilders.get("/hyena/system/dumpMemCache").param("name", pointType);

    String resBody = mockMvc.perform(builder).andReturn().getResponse().getContentAsString();
    logger.info("response = {}", resBody);
    BaseResponse res = JsonUtils.fromJson(resBody, BaseResponse.class);
    Assertions.assertEquals(HyenaConstants.RES_CODE_SUCCESS, res.getStatus());

    // add twice
    resBody = mockMvc.perform(builder).andReturn().getResponse().getContentAsString();
    logger.info("response = {}", resBody);
    res = JsonUtils.fromJson(resBody, BaseResponse.class);
    Assertions.assertEquals(HyenaConstants.RES_CODE_SUCCESS, res.getStatus());
}
 
Example #6
Source File: UserControllerUnitTest.java    From java-starthere with MIT License 6 votes vote down vote up
@Test
public void getUserByName() throws Exception
{
    String apiUrl = "/users/user/name/testing";

    Mockito.when(userService.findByName("testing")).thenReturn(userList.get(0));

    RequestBuilder rb = MockMvcRequestBuilders.get(apiUrl).accept(MediaType.APPLICATION_JSON);
    MvcResult r = mockMvc.perform(rb).andReturn(); // this could throw an exception
    String tr = r.getResponse().getContentAsString();

    ObjectMapper mapper = new ObjectMapper();
    String er = mapper.writeValueAsString(userList.get(0));

    System.out.println("Expect: " + er);
    System.out.println("Actual: " + tr);

    assertEquals("Rest API Returns List", er, tr);
}
 
Example #7
Source File: AbiControllerTest.java    From WeBASE-Front with Apache License 2.0 6 votes vote down vote up
@Test
public void testUpdateAbi() throws Exception {
	// test insert
	ReqImportAbi abiUpdate = new ReqImportAbi();
	// abi id needed in update
	abiUpdate.setAbiId(1L);
	abiUpdate.setGroupId(groupId);
	abiUpdate.setContractAddress("0xd8e1e0834b38081982f4a080aeae350a6d422915");
	abiUpdate.setContractName("Hello_222");
	String abiStr = "[{\"constant\":true,\"inputs\":[],\"name\":\"get\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256[]\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_ua\",\"type\":\"uint256[]\"}],\"name\":\"set\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]";
	abiUpdate.setContractAbi(JsonUtils.toJavaObjectList(abiStr, Object.class));

	// post action
	ResultActions resultActions = mockMvc.perform(
		MockMvcRequestBuilders.put("/abi")
			.content(JsonUtils.toJSONString(abiUpdate))
			.contentType(MediaType.APPLICATION_JSON)
	);
	resultActions.
		andExpect(MockMvcResultMatchers.status().isOk()).
		andDo(MockMvcResultHandlers.print());
	System.out
		.println("response:" + resultActions.andReturn().getResponse().getContentAsString());
}
 
Example #8
Source File: ContractControllerTest.java    From WeBASE-Front with Apache License 2.0 6 votes vote down vote up
@Test
public void testQueryContractList() throws Exception {
    ReqPageContract param = new ReqPageContract();
    param.setGroupId(groupId);
    //  param.setContractStatus(2);
     param.setContractName("a");
    // param.setContractAddress("0x19146d3a2f138aacb97ac52dd45dd7ba7cb3e04a");
    param.setPageNumber(0);
    param.setPageSize(10);
    // param.setContractAddress("bb4c11a3b38e931e");

    ResultActions resultActions = mockMvc
        .perform(MockMvcRequestBuilders.post("/contract/contractList").
            content(JsonUtils.toJSONString(param)).
            contentType(MediaType.APPLICATION_JSON)
        );
    resultActions.
        andExpect(MockMvcResultMatchers.status().isOk()).
        andDo(MockMvcResultHandlers.print());
    System.out
        .println("response:" + resultActions.andReturn().getResponse().getContentAsString());
}
 
Example #9
Source File: HtmlUnitRequestBuilder.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
public Object merge(@Nullable Object parent) {
	if (parent instanceof RequestBuilder) {
		if (parent instanceof MockHttpServletRequestBuilder) {
			MockHttpServletRequestBuilder copiedParent = MockMvcRequestBuilders.get("/");
			copiedParent.merge(parent);
			this.parentBuilder = copiedParent;
		}
		else {
			this.parentBuilder = (RequestBuilder) parent;
		}
		if (parent instanceof SmartRequestBuilder) {
			this.parentPostProcessor = (SmartRequestBuilder) parent;
		}
	}
	return this;
}
 
Example #10
Source File: UserControllerUnitTest.java    From java-starthere with MIT License 6 votes vote down vote up
@Test
public void getCurrentUserName() throws Exception
{
    String apiUrl = "/users/getusername";

    RequestBuilder rb = MockMvcRequestBuilders.get(apiUrl).accept(MediaType.APPLICATION_JSON);
    MvcResult r = mockMvc.perform(rb).andReturn(); // this could throw an exception
    String tr = r.getResponse().getContentAsString();

    String er = "{\"password\":\"password\",\"username\":\"admin\",\"authorities\":[{\"authority\":\"ROLE_ADMIN\"},{\"authority\":\"ROLE_USER\"}],\"accountNonExpired\":true,\"accountNonLocked\":true,\"credentialsNonExpired\":true,\"enabled\":true}";

    System.out.println("Expect: " + er);
    System.out.println("Actual: " + tr);

    assertEquals("Rest API Returns List", er, tr);
}
 
Example #11
Source File: ContractControllerTest.java    From WeBASE-Node-Manager with Apache License 2.0 6 votes vote down vote up
@Test
public void testQueryContractList() throws Exception {
    QueryContractParam param = new QueryContractParam();
    param.setGroupId(groupId);
    //  param.setContractStatus(2);
    // param.setContractName("OK");
    // param.setContractAddress("0x19146d3a2f138aacb97ac52dd45dd7ba7cb3e04a");
    param.setPageNumber(1);
    param.setPageSize(10);
    param.setContractAddress("bb4c11a3b38e931e");

    ResultActions resultActions = mockMvc
        .perform(MockMvcRequestBuilders.post("/contract/contractList").
            content(JsonTools.toJSONString(param)).
            contentType(MediaType.APPLICATION_JSON_UTF8)
        );
    resultActions.
        andExpect(MockMvcResultMatchers.status().isOk()).
        andDo(MockMvcResultHandlers.print());
    System.out
        .println("response:" + resultActions.andReturn().getResponse().getContentAsString());
}
 
Example #12
Source File: UserControllerTest.java    From WeBASE-Node-Manager with Apache License 2.0 6 votes vote down vote up
@Test
public void testNewUser() throws Exception {
    NewUserInputParam newUser = new NewUserInputParam();
    newUser.setUserName("cnsUser");
    newUser.setGroupId(1);

    ResultActions resultActions = mockMvc.perform(MockMvcRequestBuilders.post("/user/userInfo").
        content(JsonTools.toJSONString(newUser)).
        contentType(MediaType.APPLICATION_JSON_UTF8)
    );
    resultActions.
        andExpect(MockMvcResultMatchers.status().isOk()).
        andDo(MockMvcResultHandlers.print());
    System.out
        .println("response:" + resultActions.andReturn().getResponse().getContentAsString());
}
 
Example #13
Source File: ServiceConfigControllerTest.java    From AthenaServing with Apache License 2.0 6 votes vote down vote up
/**
 * 推送配置
 *
 * @throws Exception
 */
@Test
public void test_service_config_4_push() throws Exception {
    PushServiceConfigRequestBody body = new PushServiceConfigRequestBody();
    body.setId("3753486267610824705");
    List<String> regionIds = new ArrayList<>();
    regionIds.add("3777763353183649792");
    body.setRegionIds(regionIds);
    String result = this.mockMvc.perform(MockMvcRequestBuilders.post("/api/v1/service/config/push")
            .content(JSON.toJSONString(body))
            .contentType(MediaType.APPLICATION_JSON)
            .session((MockHttpSession) Utils.getLoginSession(this.mockMvc))
            .accept(MediaType.APPLICATION_JSON))
            .andExpect(MockMvcResultMatchers.status().isOk())
            .andDo(MockMvcResultHandlers.print())
            .andReturn().getResponse().getContentAsString();
    Utils.assertResult(result);
}
 
Example #14
Source File: ServiceDiscoveryControllerTest.java    From AthenaServing with Apache License 2.0 6 votes vote down vote up
/**
 * 查询服务提供者列表
 *
 * @throws Exception
 */
@Test
public void test_service_discovery_5_provider() throws Exception {
    String result = this.mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/service/discovery/provider")
            .param("project", "test0803")
            .param("cluster", "test0803")
            .param("service", "test0803")
            .param("apiVersion","1.0")
            .param("region", "test")
            .param("isPage", "0")
            .contentType(MediaType.APPLICATION_JSON)
            .session((MockHttpSession) Utils.getLoginSession(this.mockMvc))
            .accept(MediaType.APPLICATION_JSON))
            .andExpect(MockMvcResultMatchers.status().isOk())
            .andReturn().getResponse().getContentAsString();
    Utils.assertResult(result);
}
 
Example #15
Source File: TestPointController.java    From hyena with Apache License 2.0 6 votes vote down vote up
/**
 * 消费积分, 同时解冻积分
 */
@Test
public void test_decreaseFrozen_unfreeze() throws Exception {
    PointUsage freeze = new PointUsage();
    freeze.setPoint(BigDecimal.valueOf(14L)).setType(super.getPointType())
            .setUid(super.getUid()).setSubUid(super.getSubUid());
    this.pointUsageFacade.freeze(freeze);

    PointDecreaseFrozenParam param = new PointDecreaseFrozenParam();
    param.setType(super.getPointType());
    param.setUid(super.getUid());
    param.setSubUid(super.getSubUid());
    param.setUnfreezePoint(BigDecimal.valueOf(5L)); // 要做解冻的部分
    param.setPoint(BigDecimal.valueOf(9L)); // 要消费的部分
    RequestBuilder builder = MockMvcRequestBuilders.post("/hyena/point/decreaseFrozen")
            .contentType(MediaType.APPLICATION_JSON)
            .content(JsonUtils.toJsonString(param));

    String resBody = mockMvc.perform(builder).andReturn().getResponse().getContentAsString();
    logger.info("response = {}", resBody);
    ObjectResponse<PointOpResult> res = JsonUtils.fromJson(resBody, new TypeReference<ObjectResponse<PointOpResult>>() {

    });
    PointPo result = res.getData();
    Assertions.assertNotNull(result);
}
 
Example #16
Source File: UserControllerUnitTest.java    From java-starthere with MIT License 6 votes vote down vote up
@Test
public void updateUser() throws Exception
{
    String apiUrl = "/users/user/{userid}";

    // build a user
    User u1 = new User();
    u1.setUserid(100);
    u1.setUsername("tigerUpdated");
    u1.setPrimaryemail("[email protected]");
    u1.setPassword("ILuvM4th!");

    Mockito.when(userService.update(u1, 100L, true)).thenReturn(userList.get(0));

    ObjectMapper mapper = new ObjectMapper();
    String userString = mapper.writeValueAsString(u1);

    RequestBuilder rb = MockMvcRequestBuilders.put(apiUrl, 100L)
                                              .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)
                                              .content(userString);

    mockMvc.perform(rb).andExpect(status().is2xxSuccessful()).andDo(MockMvcResultHandlers.print());
}
 
Example #17
Source File: UserControllerTest.java    From WeBASE-Node-Manager with Apache License 2.0 6 votes vote down vote up
@Test
public void testUpdateUser() throws Exception {
    UpdateUserInputParam updateUser = new UpdateUserInputParam();
    updateUser.setUserId(700001);
    updateUser.setDescription("testtttttttttttttttttttttttt");

    ResultActions resultActions = mockMvc.perform(MockMvcRequestBuilders.put("/user/userInfo").
        content(JsonTools.toJSONString(updateUser)).
        contentType(MediaType.APPLICATION_JSON_UTF8)
    );
    resultActions.
        andExpect(MockMvcResultMatchers.status().isOk()).
        andDo(MockMvcResultHandlers.print());
    System.out
        .println("response:" + resultActions.andReturn().getResponse().getContentAsString());
}
 
Example #18
Source File: TestStationFcOpenFiles.java    From tds with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void testReq(String dataset, String req) throws Exception {
  List<String> cacheEntries = rafCache.showCache();

  RequestBuilder rb = MockMvcRequestBuilders.get(dataset + req).servletPath(dataset);
  System.out.printf("%nURL='%s'%n", dataset + req);
  ResultActions mockMvc = this.mockMvc.perform(rb);
  MvcResult result = mockMvc.andExpect(MockMvcResultMatchers.status().isOk()).andReturn();
  MockHttpServletResponse response = result.getResponse();
  // if any file in the cache is locked, the string representation of that cache entry
  // will start with true. We do not want any entry to be locked, so make sure this
  // none of these entries start with "true"
  cacheEntries = rafCache.showCache();
  int numberOfCacheEnteries = cacheEntries.size();
  boolean isAnyFileLocked = cacheEntries.stream().anyMatch(entry -> entry.startsWith("true"));
  assertThat(isAnyFileLocked).isFalse();

  // make another request for the same data
  // the cache should not change in size. If so, we're not releasing
  // resources properly.
  mockMvc = this.mockMvc.perform(rb);
  MvcResult result2 = mockMvc.andExpect(MockMvcResultMatchers.status().isOk()).andReturn();
  MockHttpServletResponse response2 = result2.getResponse();

  cacheEntries = rafCache.showCache();
  // make sure we didn't end up with more or less files in the cache after a new request
  assertThat(numberOfCacheEnteries).isEqualTo(cacheEntries.size());
  // make sure none of the entries are locked
  isAnyFileLocked = cacheEntries.stream().anyMatch(entry -> entry.startsWith("true"));
  assertThat(isAnyFileLocked).isFalse();

  // Not directly related to the resource issue, but while we're here, let's
  // make sure the first and second requests, which are identical, return the same data.
  assertThat(response.getContentAsByteArray()).isEqualTo(response2.getContentAsByteArray());
}
 
Example #19
Source File: IntegrationResourceTest.java    From heimdall with Apache License 2.0 5 votes vote down vote up
@Test
@WithMockUser(username="tester", authorities={"CREATE_ACCESSTOKEN"})
public void testSavingDeveloperWithoutRequiredField() throws Exception {          
     Mockito.when(developerService.save(Mockito.any(DeveloperDTO.class))).thenReturn(new Developer());
     
     mockMvc.perform(MockMvcRequestBuilders.post(ConstantsPath.PATH_INTEGRATION_RESOURCES+"/developer/callback")
            .content("{\"name\":\"NoNamebypass\",\"status\":\"ACTIVE\"}")
            .contentType(MediaType.APPLICATION_JSON))
            .andExpect(MockMvcResultMatchers.status().is4xxClientError())
            .andExpect(MockMvcResultMatchers.content().json("{\"status\":400,\"exception\":\"MethodArgumentNotValidException\",\"erros\":[{\"defaultMessage\":\"may not be null\",\"field\":\"email\",\"code\":\"NotNull\"}]}"));
}
 
Example #20
Source File: TodoControllerTest.java    From Mastering-Spring-5.1 with MIT License 5 votes vote down vote up
@Test
public void createTodo() throws Exception {
	Todo mockTodo = new Todo(CREATED_TODO_ID, "Jack", "Learn Spring MVC", new Date(), false);
	String todo = "{\"user\":\"Jack\",\"desc\":\"Learn Spring MVC\",\"done\":\"false\"}";

	when(service.addTodo(anyString(), anyString(), isNull(), anyBoolean())).thenReturn(mockTodo);
	mvc.perform(
			MockMvcRequestBuilders.post("/users/Jack/todos").content(todo).contentType(MediaType.APPLICATION_JSON))
			.andExpect(status().isCreated())
			.andExpect(header().string("location", containsString("/users/Jack/todos/" + CREATED_TODO_ID)));
}
 
Example #21
Source File: BrokerControllerTest.java    From WeEvent with Apache License 2.0 5 votes vote down vote up
@Test
public void testAddBrokerException001() throws Exception {
    String content = "{\"name\":\"broker\",\"brokerUrl\":\"" + this.brokerUrl + "\",\"userId\":\"1\"}";
    MockHttpServletResponse response = mockMvc.perform(MockMvcRequestBuilders.post("/broker/add").contentType(MediaType.APPLICATION_JSON_UTF8).header(JwtUtils.AUTHORIZATION_HEADER_PREFIX, token).content(content))
            .andReturn().getResponse();
    Assert.assertEquals(response.getStatus(), HttpStatus.SC_OK);
    GovernanceResult governanceResult = JsonHelper.json2Object(response.getContentAsString(), GovernanceResult.class);
    Assert.assertEquals("100108", governanceResult.getStatus().toString());
}
 
Example #22
Source File: ServiceControllerTest.java    From AthenaServing with Apache License 2.0 5 votes vote down vote up
/**
 * 删除服务
 *
 * @throws Exception
 */
@Test
public void test_service_3_delete() throws Exception {
    IdRequestBody body = new IdRequestBody();
    body.setId("3714708188751200256");
    String result = this.mockMvc.perform(MockMvcRequestBuilders.post("/api/v1/service/delete")
            .content(JSON.toJSONString(body))
            .contentType(MediaType.APPLICATION_JSON)
            .session((MockHttpSession) Utils.getLoginSession(this.mockMvc))
            .accept(MediaType.APPLICATION_JSON))
            .andExpect(MockMvcResultMatchers.status().isOk())
            .andDo(MockMvcResultHandlers.print())
            .andReturn().getResponse().getContentAsString();
    Utils.assertResult(result);
}
 
Example #23
Source File: TbContentControllerTests.java    From spring-boot-samples with Apache License 2.0 5 votes vote down vote up
/**
 * 更新资源
 *
 * @throws Exception
 */
@Test
public void testUpdate() throws Exception {
    // 由于请求参数使用了 @RequestBody 注解,故需要将参数封装成 JSON 格式
    TbContent tbContent = new TbContent();
    tbContent.setId(43L);
    tbContent.setCategoryId(89L);
    tbContent.setTitle("来自 SpringMock 的编辑测试");
    ObjectMapper objectMapper = new ObjectMapper();
    ObjectWriter objectWriter = objectMapper.writer().withDefaultPrettyPrinter();
    String jsonParams = objectWriter.writeValueAsString(tbContent);

    // 模拟请求
    int status = this.mockMvc
            .perform(MockMvcRequestBuilders
                    .put("/update")
                    .header("Authorization", "Bearer 91317816-5036-4b76-86b7-05d96d55774d")
                    // 设置使用 JSON 方式传参
                    .contentType(MediaType.APPLICATION_JSON)
                    // 设置 JSON 参数内容
                    .content(jsonParams))
            .andDo(MockMvcResultHandlers.print())
            .andReturn().getResponse().getStatus();
    if (status == 200) {
        log.info("请求成功");
    } else {
        log.info("请求失败,状态码为:{}", status);
    }

    Assert.assertEquals(status, 200);
}
 
Example #24
Source File: ServiceControllerTest.java    From AthenaServing with Apache License 2.0 5 votes vote down vote up
/**
 * 查询服务明细
 *
 * @throws Exception
 */
@Test
public void test_service_5_detail() throws Exception {
    String result = this.mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/service/detail")
            .param("id", "3716423263660802048")
            .contentType(MediaType.APPLICATION_JSON)
            .session((MockHttpSession) Utils.getLoginSession(this.mockMvc))
            .accept(MediaType.APPLICATION_JSON))
            .andExpect(MockMvcResultMatchers.status().isOk())
            .andDo(MockMvcResultHandlers.print())
            .andReturn().getResponse().getContentAsString();
    Utils.assertResult(result);
}
 
Example #25
Source File: ServiceTest.java    From WeEvent with Apache License 2.0 5 votes vote down vote up
@Test
public void absHitRule() throws Exception {
    String arr = "[[\"0\", \"6\", \"floor\", \"c\"]]";
    rule.setFromDestination("from.com.weevent.test");
    rule.setPayload("{\"a\":1,\"b\":\"test\",\"c\":10}");
    rule.setSelectField("a,eventId,topicName,brokerId,groupId");
    rule.setConditionField("abs(c)<10");
    rule.setToDestination("to.com.weevent.test");
    rule.setFunctionArray(arr);
    rule.setConditionType(2);
    RequestBuilder requestBuilder3 = MockMvcRequestBuilders.post(url).contentType(MediaType.APPLICATION_JSON).content(JsonHelper.object2Json(rule));
    MvcResult result3 = mockMvc.perform(requestBuilder3).andDo(print()).andReturn();
    log.info("result3:{}", result3.getResponse().getStatus());
    assertEquals(200, result3.getResponse().getStatus());
}
 
Example #26
Source File: AccountControllerTest.java    From WeEvent with Apache License 2.0 5 votes vote down vote up
@Test
public void testUpdatePasswordException002() throws Exception {
    String content = "{\"username\":\"zjy05\",\"oldPassword\":\"123456qqq\",\"password\":\"\"}";
    MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.post("/user/update").contentType(MediaType.APPLICATION_JSON_UTF8).content(content))
            .andReturn();
    MockHttpServletResponse response = mvcResult.getResponse();
    Assert.assertEquals(response.getStatus(), HttpStatus.SC_OK);
    GovernanceResult governanceResult = JsonHelper.json2Object(response.getContentAsString(), GovernanceResult.class);
    Assert.assertEquals("400", governanceResult.getStatus().toString());
}
 
Example #27
Source File: TranslationCollectKeyAPITest.java    From singleton with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void test003collectV1KeyTranslationNoComponent() throws Exception {
	MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(
			webApplicationContext).build();
	String API = L10nI18nAPI.TRANSLATION_PRODUCT_NOCOMOPONENT_KEY_APIV1
			.replace("{" + APIParamName.PRODUCT_NAME + "}", "NOComponent")
			//.replace("{" + APIParamName.COMPONENT + "}", "default")
			.replace("{" +APIParamName.KEY+ "}", "dc.myhome.open3");
	MvcResult mvcRS =mockMvc.perform(
			MockMvcRequestBuilders.post(API)
			        .param(Constants.VERSION, "1.1.0")
			        .param(APIParamName.LOCALE, "en")
					.param(APIParamValue.SOURCE, "this open3's value")
					.param(APIParamName.COMMENT_SOURCE, "dc new string")
					.param(APIParamName.SOURCE_FORMAT, "")
					.param(APIParamName.COLLECT_SOURCE, "true")
					.accept(MediaType.APPLICATION_JSON))
			.andExpect(status().isOk()).andReturn();
	
	 String resultStr =   mvcRS.getResponse().getContentAsString();
	   
	   logger.info(resultStr);
	
	   MvcResult mvcRS2 =mockMvc.perform(
				MockMvcRequestBuilders.post(API)
				        .param(Constants.VERSION, "1.1.0")
				        .param(APIParamName.LOCALE, "en")
						.param(APIParamValue.SOURCE, "this open3's value")
						.param(APIParamName.COMMENT_SOURCE, "dc new string")
						.param(APIParamName.COLLECT_SOURCE, "true")
						.accept(MediaType.APPLICATION_JSON))
				.andExpect(status().isOk()).andReturn();
		
		 String resultStr2 =   mvcRS2.getResponse().getContentAsString();
		   
		   logger.info(resultStr2);
}
 
Example #28
Source File: BrokerControllerTest.java    From WeEvent with Apache License 2.0 5 votes vote down vote up
public void deleteBroker() throws Exception {
    String content = "{\"id\":" + this.brokerIdMap.get("brokerId") + ",\"userId\":\"1\"}";
    MockHttpServletResponse response = mockMvc.perform(MockMvcRequestBuilders.post("/broker/delete").contentType(MediaType.APPLICATION_JSON_UTF8).header(JwtUtils.AUTHORIZATION_HEADER_PREFIX, token).content(content))
            .andReturn().getResponse();
    Assert.assertEquals(response.getStatus(), HttpStatus.SC_OK);
    Map jsonObject = JsonHelper.json2Object(response.getContentAsString(), Map.class);
    Assert.assertEquals(jsonObject.get("status").toString(), "200");
}
 
Example #29
Source File: TestPointFCExceptions.java    From tds with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void invalidTimeRange() throws Exception {
  RequestBuilder rb = MockMvcRequestBuilders.get(dataset).servletPath(dataset).param("accept", "netcdf")
      .param("north", "43.0").param("south", "38.0").param("west", "-107.0").param("east", "-103.0")
      .param("time_start", "2006-03-02T00:00:00Z").param("time_end", "2006-03-28T00:00:00Z")
      .param("var", "ICE, PRECIP_amt");

  this.mockMvc.perform(rb).andExpect(MockMvcResultMatchers.status().is(400));
}
 
Example #30
Source File: ServiceTest.java    From WeEvent with Apache License 2.0 5 votes vote down vote up
@Test
public void deleteRule() throws Exception {
    String url = "/deleteCEPRuleById";

    RequestBuilder requestBuilder = MockMvcRequestBuilders.post(url).contentType(MediaType.APPLICATION_JSON).param("id", "1111");
    MvcResult result = mockMvc.perform(requestBuilder).andDo(print()).andReturn();
    log.info("result:{}", result.getResponse().getContentAsString());
    assertEquals(200, result.getResponse().getStatus());
}