title: JUnit5 test a secured controller in using Spring security
body: <p>I have a simple controller that should only be accessible in a secured context.
  In my application, I only whitelist other URLs, not <code>/user</code>.</p>
  
  <p>In the unit test for the single <code>@GetResponse</code> I get an Http Status of 401 instead of a 200. I expect this, as it is secured. </p>
  
  <p>When I actually run the application with a logged in user, I get a 200, and a valid result.</p>
  
  <p>How can I Unit Test the behaviour of the request and any other secured controller paths?</p>
  
  <p>Unit test:</p>
  
  <pre><code>@SpringBootTest
  @AutoConfigureMockMvc
  class UserControllerTest {
  
    @InjectMocks
    UserController userController;
    @Autowired
    private MockMvc mockMvc;
    @Autowired
    private ApplicationContext applicationContext;
  
    @Test
    void getUserNone() throws Exception {
  
      mockMvc
          .perform(MockMvcRequestBuilders.get("/user"))
          .andExpect(status().isOk());
    }
  }
  </code></pre>
  
  <p>App:</p>
  
  <pre><code>@SpringBootApplication
  public class WebApp extends WebSecurityConfigurerAdapter {
  
    public static void main(final String... args) {
      SpringApplication.run(WebApp.class, args);
    }
  
    @Override
    protected void configure(final HttpSecurity http) throws Exception {
      http
          .authorizeRequests(a -&gt; a
              .antMatchers("/error", "/css/**", "/webjars/**").permitAll()
              .anyRequest().authenticated()
          )
          .exceptionHandling(e -&gt; e
              .authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED))
          )
          .oauth2Login();
    }   
  }
  </code></pre>
  
  <p>Controller:</p>
  
  <pre><code>@Controller
  public class UserController {
  
    @GetMapping("/user")
    public @ResponseBody
    Map&lt;String, Object&gt; getUser(@AuthenticationPrincipal final OAuth2User principal) {
      if (principal == null) {
        return Collections.EMPTY_MAP;
      } else {
        return Collections.singletonMap("name", principal.getName());
      }   
    }
  }
  </code></pre>
  
  <p>Obviously, I could add <code>/user</code> to the whitelisted paths, but that would be incorrect for any secured parts of the application.</p>