I want to write unit tests for my spring controller. I\'m using keycloak\'s openid flow to secure my endpoints.
In my tests I\'m using the @WithMockUser
ann
I was able to test after adding the following things:
Add some fields:
@Autowired
private WebApplicationContext context;
private MockMvc mockMvc;
In my @Before
setup()
method:
mockMvc = MockMvcBuilders.webAppContextSetup(context)
.alwaysDo(print())
.apply(springSecurity())
.build();
Inside my test method:
SecurityContext context = SecurityContextHolder.getContext();
Authentication authentication = context.getAuthentication();
When I pass the authentication
object to the method where I read the claims from the keycloak token I can run the test without any problems.
P.S. Don't forget the @WithMockUser
annotation