-1

I have started to use @PreAuthorize, which i want to test using testNg. I am using withUserContext("username"); But every test I run gets passed but in real time the authorisation is done perfectly in the portal. Can someone help me out of this.

@Test
private void testFunctionWith@PreAuthorize() throws Exception {
   withUserContext("username");
}
public SecurityContext withUserContext(String username) {
    UserDetails principal = asyncCall(username);
    Authentication authentication = new UsernamePasswordAuthenticationToken(principal, principal.getPassword(),
            principal.getAuthorities());
    SecurityContext context = SecurityContextHolder.getContext();
    context.setAuthentication(authentication);

    return context;
}

@Async
public UserDetails asyncCall(String username) {
    return userDetailsService.loadUserByUsername(username);
}

The tests that are expected to fail are getting passed.

Yash
  • 11,486
  • 4
  • 19
  • 35
shashank
  • 11
  • 7

1 Answers1

0

You should use the mvcPerform suite and mvcMock.

McvMock will mock your security filter chain, filters and mic context, instead mvcPerform will perform the http calls validating the responses (type, status, content and so on)

MvcPerform example: https://www.baeldung.com/integration-testing-in-spring