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

The following examples show how to use org.springframework.test.web.servlet.request.MockMvcRequestBuilders. These examples are extracted from open source projects. 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 Project: WeBASE-Front   Source File: TransControllerTest.java    License: 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 Project: WeBASE-Front   Source File: Web3ApiControllerTest.java    License: 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 3
@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 4
Source Project: hyena   Source File: TestPointController.java    License: 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 5
Source Project: AthenaServing   Source File: ServiceConfigControllerTest.java    License: 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 6
/**
 * 查询服务提供者列表
 *
 * @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 7
Source Project: hyena   Source File: TestPointController.java    License: 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 8
Source Project: WeBASE-Node-Manager   Source File: UserControllerTest.java    License: 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 9
Source Project: WeBASE-Front   Source File: AbiControllerTest.java    License: 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 10
Source Project: java-starthere   Source File: UserControllerUnitTest.java    License: 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 11
Source Project: WeBASE-Node-Manager   Source File: UserControllerTest.java    License: 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 12
@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 13
Source Project: java-starthere   Source File: UserControllerUnitTest.java    License: 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 14
Source Project: java-technology-stack   Source File: HtmlUnitRequestBuilder.java    License: 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 15
Source Project: WeBASE-Front   Source File: ContractControllerTest.java    License: 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 16
Source Project: java-starthere   Source File: UserControllerUnitTest.java    License: 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 17
Source Project: hyena   Source File: TestSystemController.java    License: 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 18
Source Project: das   Source File: UserControllerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void update() throws Exception {
    mockMvc.perform(MockMvcRequestBuilders.put("/user/update")
            .contentType(MediaType.APPLICATION_JSON_UTF8)
            .content(requestJson)
            .accept(MediaType.APPLICATION_JSON_UTF8))
            .andExpect(MockMvcResultMatchers.status().isOk())
            .andDo(MockMvcResultHandlers.print());
}
 
Example 19
Source Project: das   Source File: GroupDatabaseControllerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void getDBListByGroupId() throws Exception {
    mockMvc.perform(MockMvcRequestBuilders.get("/groupdb/dblist")
            .contentType(MediaType.APPLICATION_JSON_UTF8)
            .accept(MediaType.APPLICATION_JSON_UTF8))
            .andExpect(MockMvcResultMatchers.status().isOk())
            .andDo(MockMvcResultHandlers.print());
}
 
Example 20
@Test
public void showCommandTest() throws Exception {
  RequestBuilder rb =
      MockMvcRequestBuilders.get(path).servletPath(path).param("command", "SHOW").param("catalog", catalog);

  MvcResult result = this.mockMvc.perform(rb).andExpect(MockMvcResultMatchers.status().is(200))
      .andExpect(MockMvcResultMatchers.content().contentType(htmlContent)).andReturn();

  System.out.printf("showCommandTest status=%d%n", result.getResponse().getStatus());
  System.out.printf("%s%n", result.getResponse().getContentAsString());
}
 
Example 21
Source Project: Mastering-Spring-5.1   Source File: TodoControllerTest.java    License: MIT License 5 votes vote down vote up
@Test
public void createTodo_withValidationError() throws Exception {
	Todo mockTodo = new Todo(CREATED_TODO_ID, "Jack", "Learn Spring MVC", new Date(), false);
	String todo = "{\"user\":\"Jack\",\"desc\":\"Learn\",\"done\":\"false\"}";
	when(service.addTodo(anyString(), anyString(), isNull(), anyBoolean())).thenReturn(mockTodo);
	MvcResult result = mvc.perform(
			MockMvcRequestBuilders.post("/users/Jack/todos").content(todo).contentType(MediaType.APPLICATION_JSON))
			.andExpect(status().is4xxClientError()).andReturn();
}
 
Example 22
Source Project: Mastering-Spring-5.1   Source File: TodoControllerTest.java    License: MIT License 5 votes vote down vote up
@Test
public void deleteTodo() throws Exception {
	Todo mockTodo = new Todo(1, "Jack", "Learn Spring MVC", new Date(), false);
	when(service.deleteById(anyInt())).thenReturn(mockTodo);
	mvc.perform(MockMvcRequestBuilders.delete("/users/Jack/todos/" + mockTodo.getId())
			.accept(MediaType.APPLICATION_JSON)).andExpect(status().isNoContent());
}
 
Example 23
Source Project: WeEvent   Source File: ServiceTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void checkConditionRight2() throws Exception {
    String url = "/checkWhereCondition";

    RequestBuilder requestBuilder = MockMvcRequestBuilders.get(url).contentType(MediaType.APPLICATION_JSON).param("payload", "{\"a\":1,\"b\":\"test\",\"c\":10}").param("condition", "c<10 and (c=\"test\")");
    MvcResult result = mockMvc.perform(requestBuilder).andDo(print()).andReturn();
    log.info("result:{}", result.getResponse().getContentAsString());
    assertEquals(200, result.getResponse().getStatus());
}
 
Example 24
Source Project: WeEvent   Source File: RuleEngineControllerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testUpdateRuleEngineException001() throws Exception {
    String content = "{\"id\":\"" + ruleMap.get("ruleId") + "\",\"ruleName\":\"\",\"payloadType\":\"1\"," +
            "\"payloadMap\":{\"temperate\":30,\"humidity\":0.5},\"brokerId\":\"" + this.ruleMap.get("brokerId") + "\"," +
            "\"fromDestination\":\"com.weevent.stomp\",\"toDestination\":\"com.weevent.test\",\"com.weevent.mqtt\":\"test\"," +
            "\"selectField\":\"temperate\",\"conditionField\":\"temperate>38\",\"conditionType\":\"1\"}";
    MockHttpServletResponse response = mockMvc.perform(MockMvcRequestBuilders.post("/ruleEngine/update").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("code").toString(), "-1");
}
 
Example 25
Source Project: rebuild   Source File: UserControllTest.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testEnableUser() throws Exception {
	String post = String.format(
			"{ user:'%s', enable:true, role:'%s', dept:'%s' }", 
			SIMPLE_USER, SIMPLE_ROLE, SIMPLE_DEPT);
	
	MockHttpServletRequestBuilder builder = MockMvcRequestBuilders
			.post("/admin/bizuser/enable-user")
			.content(post)
			.sessionAttr(WebUtils.KEY_PREFIX + "-AdminVerified", "Mock");
	
	MvcResponse resp = perform(builder, UserService.ADMIN_USER);
	System.out.println(resp);
	Assert.assertTrue(resp.isSuccess());
}
 
Example 26
Source Project: rebuild   Source File: ApiGatewayTest.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testSimple() throws Exception {
    final String[] app = createApp();

    String apiUrl = "/gw/api/system-time?";
    Map<String, Object> bizParams = new HashMap<>();

    apiUrl += new OpenApiSDK(app[0], app[1]).signMD5(bizParams);
    System.out.println("Request API : " + apiUrl);

    MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get(apiUrl);
    MvcResponse resp = perform(builder, null);
    System.out.println(resp);
}
 
Example 27
Source Project: das   Source File: GroupControllerTest2.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void loadPageList() throws Exception {
    Paging<DatabaseSetEntryView> paging = new Paging<>();
    paging.setData(new DatabaseSetEntryView());
    String requestJson = JSONObject.toJSONString(paging);
    mockMvc.perform(MockMvcRequestBuilders.post("/groupdbSetEntry/list")
            .contentType(MediaType.APPLICATION_JSON_UTF8)
            .content(requestJson)
            .accept(MediaType.APPLICATION_JSON_UTF8))
            .andExpect(MockMvcResultMatchers.status().isOk())
            .andDo(MockMvcResultHandlers.print());
}
 
Example 28
/**
 * 新增资源
 */
@Test
public void testInsert() throws Exception {
    // 由于请求参数使用了 @RequestBody 注解,故需要将参数封装成 JSON 格式
    TbContent tbContent = new TbContent();
    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
                    .post("/insert")
                    .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 29
Source Project: das   Source File: GroupControllerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void getMemberGroups() throws Exception {
    mockMvc.perform(MockMvcRequestBuilders.get("/group/member/tree")
            .contentType(MediaType.APPLICATION_JSON_UTF8)
            .accept(MediaType.APPLICATION_JSON_UTF8))
            .andExpect(MockMvcResultMatchers.status().isOk())
            .andDo(MockMvcResultHandlers.print());
}
 
Example 30
Source Project: java-starthere   Source File: UserControllerIntegrationTest.java    License: MIT License 5 votes vote down vote up
@WithUserDetails("admin")
@Test
public void deleteUserById() throws Exception
{
    mockMvc.perform(MockMvcRequestBuilders.delete("/users/user/{id}",
                                                  13))
           .andDo(print())
           .andExpect(status().is2xxSuccessful());
}