title: How to unit test a SpringBoot controller secured by keycloak?
body: <p>I know that there are already similar questions, <a href="https://stackoverflow.com/questions/49144953/mocking-a-keycloak-token-for-testing-a-spring-controller">here</a> and <a href="https://stackoverflow.com/questions/51711268/how-to-test-keycloak-authentication-in-spring-boot-application">here</a>, regarding this problem but every solution proposed failed to help me. There is also mention to <a href="https://github.com/ch4mpy/spring-addons" rel="noreferrer">this</a> library in most of those answers but (with all due respect) I would like to avoid depending on an external library just to be able to test a simple controller. </p>
  
  <p>So, I have a very simple api that is accessed using a bearer token generated by keycloak and I would like to test the controller. Something along these lines:</p>
  
  <pre><code>@Test
  @DisplayName("Should be ok")
  @WithMockUser
  void whenCalled_shouldBeOk() throws Exception {
      SecurityContext context = SecurityContextHolder.getContext();
      Authentication authentication = context.getAuthentication();
      mockMvc.perform(
          post("/api/url/something")
              .content("{}")
              .contentType(APPLICATION_JSON)
              .with(authentication(authentication))
      ).andExpect(status().isOk());
  }
  </code></pre>
  
  <p>The problem is that I will always get a null pointer exception thrown by the <code>KeycloakDeploymentBuilder</code> for it's missing the adapter config. In our SecurityConfig we extend the <code>KeycloakWebSecurityConfigurerAdapter</code> and do all the required configurations for the app to work but I am failing to mock/by-pass this process in the test. Normally I find my way around this authentication problems in the tests (when keycloak isn't used) with @WithMockUser annotation but not this time.</p>
  
  <p>Isn't there way to mock the adapter or the filter process in order to by-pass this issue?</p>
  
  <p>I have tried everything that was answered in the other questions (except the library) with no luck. If you have any clue that could be of help or at least point me in the correct direction (since this can be due to a lack of knowledge on spring security from my part) that would very much appreciated.</p>