StefanSchubert / sabi

Seawater Aquarium Business Intelligence (sabi) aims to gain knowledge from aquarists for aquarists based on collected seawater parameters.
https://sabi-project.net
MIT License
4 stars 3 forks source link

Unauthorized Test with rest template shows strange behavior #28

Closed StefanSchubert closed 6 years ago

StefanSchubert commented 6 years ago

Unexpected result by the test below is:

org.springframework.http.InvalidMediaTypeException: Invalid mime type "text;charset=ISO-8859-1": does not contain '/'

@Test
/**
 * Test to check that our WebSecurityConfig is effective.
 */
public void testUnauthorizedListUsersTankRequest() throws Exception {

    // Given User presentation by a faked auth token
    String authToken = "faked";

    // when this authorized user requests his aquarium list
    HttpHeaders headers = new HttpHeaders();
   // headers.setContentType(MediaType.APPLICATION_JSON);
    headers.add("Authorization", "Bearer " + authToken);

    HttpEntity<String> requestEntity = new HttpEntity<>(headers);
    ResponseEntity<String> responseEntity = restTemplate.exchange("/api/tank/list" , HttpMethod.GET, requestEntity, String.class);

    // then we should get a 403 as result.
    assertThat(responseEntity.getStatusCode(), equalTo(HttpStatus.FORBIDDEN));

}

Strange is that this testcase was derived by this one which is running with no complains:

@Test
public void testListUsersTank() throws Exception {
    // given some Testdata via mocking

    UserTo userTo = new UserTo();
    userTo.setEmail(MOCKED_USER);
    userTo.setId(1L);
    given(this.userDao.loadUserByEmail(MOCKED_USER)).willReturn(userTo);

    List<AquariumTo> testAquariums = new ArrayList<>(1);
    AquariumTo aquariumTo = getTestAquariumFor(userTo);
    testAquariums.add(aquariumTo);

    given(this.aquariumDao.findUsersTanks(userTo.getId())).willReturn(testAquariums);

    // and we need a valid authentication token for oure mocked user
    String authToken = TokenAuthenticationService.createAuthorizationTokenFor(MOCKED_USER);

    // when this authorized user requests his aquarium list
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    headers.add("Authorization", "Bearer " + authToken);

    HttpEntity<String> requestEntity = new HttpEntity<>(headers);

    // Notice the that the controller defines a list, the resttemplate will get it as array.
    ResponseEntity<String> responseEntity = restTemplate.exchange("/api/tank/list" , HttpMethod.GET, requestEntity, String.class);

    // then we should get a 202 as result.
    assertThat(responseEntity.getStatusCode(), equalTo(HttpStatus.ACCEPTED));

    // and our test aquarium
    AquariumTo[] myObjects = objectMapper.readValue(responseEntity.getBody(), AquariumTo[].class);
    assertThat(Arrays.asList(myObjects), hasItem(aquariumTo));

}
StefanSchubert commented 6 years ago

fixed by #29