· 8 years ago · Dec 04, 2016, 04:28 AM
1private String getAccessToken() throws Exception {
2 String urlString = "/oauth/token";
3 HttpEntity<MultiValueMap<String, String>> request = getAccessTokenRequest();
4
5 ResponseEntity<JSONObject> responseEntity = restTemplate
6 .exchange(urlString, HttpMethod.POST, request, JSONObject.class);
7 assertEquals(HttpStatus.OK, responseEntity.getStatusCode());
8
9 JSONObject userJson = responseEntity.getBody();
10 assertNotNull(userJson.get("access_token"));
11 assertEquals("bearer", userJson.get("token_type"));
12
13 return userJson.getString("access_token");
14}
15
16private HttpEntity<MultiValueMap<String, String>> getAccessTokenRequest() {
17 HttpHeaders headers = new HttpHeaders();
18 headers = setBasicAuthHeaders(headers);
19 headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
20 headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
21
22 MultiValueMap<String, String> requestMap = new LinkedMultiValueMap<>();
23 requestMap.add("grant_type", "client_credentials");
24 return new HttpEntity<>(requestMap, headers);
25}
26
27private HttpHeaders setBasicAuthHeaders(HttpHeaders headers) {
28 String authorization = "Basic " + new String(Base64Utils.encode("test:testsecret".getBytes()));
29 headers.add("Authorization", authorization);
30 return headers;
31}
32
33@Test
34public void createCustomer() throws Exception {
35 String accessToken = getAccessToken();
36
37 HttpHeaders headers = new HttpHeaders();
38 headers.add("Bearer", accessToken);
39 HttpEntity<String> entity = new HttpEntity<>(headers);
40
41 ResponseEntity<Customer> responseEntity = restTemplate
42 .exchange("/api/2.0/customers/save"+
43 "?firstName=" + customerToSave.getFirstName() +
44 "&lastName=" + customerToSave.getLastName(),
45 HttpMethod.GET, entity, Customer.class);
46
47 Customer customer = responseEntity.getBody();
48 assertEquals(HttpStatus.OK, responseEntity.getStatusCode());
49 assertEquals(customerToSave.getLastName(), customer.getLastName());
50}
51
52@ActiveProfiles("test")
53@RunWith(SpringRunner.class)
54@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)