Reputation: 65
My test cases are failing in controller class due to spring security.
@PostMapping("/{username}")
@PreAuthorize("hasRole('MEMBER') && #username == authentication.principal.username")
public ResponseEntity<Object> addWishlist(@Parameter(hidden = true) @RequestHeader("Authorization") String token, @PathVariable String username, @RequestBody MovieDto movie){
return new ResponseEntity<>(wishlistService.addWishlist(username,movie),HttpStatus.CREATED);
}
testcase
@Test
@WithMockUser(roles = "MEMBER", username = "user")
void testAddWishlist() throws Exception {
String username = "user";
MovieDto movieDto = new MovieDto();
movieDto.setTitle("Movie 1");
WishlistDto wishlistDto = new WishlistDto();
wishlistDto.setUsername(username);
wishlistDto.setMovies(List.of(movieDto));
when(wishlistService.addWishlist(username, movieDto)).thenReturn(wishlistDto);
mockMvc.perform(MockMvcRequestBuilders.post("/api/v1.0/private/wishlist/{username}", username)
.header(HttpHeaders.AUTHORIZATION, "Bearer testtoken")
.content("{\"id\":\"1\",\"title\":\"Movie 1\"}")
.contentType(MediaType.APPLICATION_JSON))
.andExpect(MockMvcResultMatchers.status().isCreated())
.andExpect(MockMvcResultMatchers.jsonPath("$.movies[0].title").value("Movie 1"));
}
error
MockHttpServletRequest:
HTTP Method = POST
Request URI = /api/v1.0/private/wishlist/user
Parameters = {}
Headers = [Content-Type:"application/json;charset=UTF-8", Authorization:"Bearer testtoken", Content-Length:"28"]
Body = {"id":"1","title":"Movie 1"}
Session Attrs = {org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository.CSRF_TOKEN=org.springframework.security.web.csrf.DefaultCsrfToken@46bfbbb9, SPRING_SECURITY_CONTEXT=SecurityContextImpl [Authentication=UsernamePasswordAuthenticationToken [Principal=org.springframework.security.core.userdetails.User [Username=user, Password=[PROTECTED], Enabled=true, AccountNonExpired=true, CredentialsNonExpired=true, AccountNonLocked=true, Granted Authorities=[ROLE_MEMBER]], Credentials=[PROTECTED], Authenticated=true, Details=null, Granted Authorities=[ROLE_MEMBER]]]}
Handler:
Type = null
Async:
Async started = false
Async result = null
Resolved Exception:
Type = null
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 403
Error message = Forbidden
Headers = [Vary:"Origin", "Access-Control-Request-Method", "Access-Control-Request-Headers", X-Content-Type-Options:"nosniff", X-XSS-Protection:"0", Cache-Control:"no-cache, no-store, max-age=0, must-revalidate", Pragma:"no-cache", Expires:"0", X-Frame-Options:"DENY"]
Content type = null
Body =
Forwarded URL = null
Redirected URL = null
Cookies = []
java.lang.AssertionError: Status expected:<201> but was:<403>
Expected :201
Actual :403
<Click to see difference>
at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:59)
at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:122)
at org.springframework.test.web.servlet.result.StatusResultMatchers.lambda$matcher$9(StatusResultMatchers.java:637)
at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:214)
at com.cts.wishlistservice.controller.WishlistControllerTestMvc.testAddWishlist(WishlistControllerTestMvc.java:102)
at java.base/java.lang.reflect.Method.invoke(Method.java:580)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1597)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1597)
If you're interested in contributing to the project, your help with testing would be greatly appreciated. I've recently enhanced the microservice with Spring Security, but the test cases are failing. If you can assist with the testing, I'll review and merge your code.
Check out the enhanced source code wishlist-service for more details. Original source code wishlist-service
Thank you!
Upvotes: 0
Views: 44
Reputation: 123
My guess is that #username == authentication.principal.username
is the culprit for this. You can try debugging on that side in order to figure out what is configured wrong.
Upvotes: 0