title: How to prevent NestedServletException when testing Spring endpoints?
body: <p>I am trying to <strong>test the security configuration</strong> of some of my endpoints which are secured with <code>@PreAuthorize(#oauth2.hasScope('scope')</code>. When accessing such an endpoint via Postman with a access token that does not have the required scope, the following is returned with HTTP status code 403 (forbidden):</p>
  
  <pre><code>{
      "error": "insufficient_scope",
      "error_description": "Insufficient scope for this resource",
      "scope": "scope"
  }
  </code></pre>
  
  <p>Which is the expected behaviour that I want.</p>
  
  <p>When trying to test this configuration, Springs <code>NestedServletException</code> interferes with my test case before it can complete with my expected result.</p>
  
  <p>This is a simplified version of the controller I want to test:</p>
  
  <pre><code>@RestController
  @RequestMapping(value = "/api")
  public class OauthTestingResource {
  
      @PreAuthorize(#oauth2.hasScope('scope'))
      @RequestMapping(value = "/scope", method = RequestMethod.GET)
      public void endpoint() {
          // ...
      }
  }
  </code></pre>
  
  <p>And this is the corresponding test case:</p>
  
  <pre><code>@RunWith(SpringJUnit4ClassRunner.class)
  @SpringBootTest(classes = MyApplication.class)
  @WebAppConfiguration
  public class AuthorizationTest {
  
      @Autowired
      protected WebApplicationContext webApplicationContext;
  
      protected SecurityContext securityContext = Mockito.mock(SecurityContext.class);
  
      @Before
      public void setup() throws Exception {
  
          this.mvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
          SecurityContextHolder.setContext(securityContext);
      }
  
      protected Authentication createMockAuth(Client client) {
  
          final List&lt;GrantedAuthority&gt; authorities = new ArrayList&lt;&gt;();
          authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
  
          final Authentication pwAuth = new UsernamePasswordAuthenticationToken("testuser", "testpw", authorities);
  
          final TokenRequest request = new TokenRequest(new HashMap&lt;&gt;(), client.getClientId(), client.getScopes(), "password");
  
          final OAuthClient oauthClient = new OAuthClient(client, GrantType.PASSWORD);
  
          return new OAuth2Authentication(request.createOAuth2Request(oauthClient), pwAuth);
      }
      @Test
      public void testAppScope() throws Exception {
  
          final Client client = new Client("id1", "secret1");
  
          client.setScope("scope");
          Mockito.when(securityContext.getAuthentication()).thenReturn(createMockAuth(client));
          // this test passes
          mvc.perform(get("/api/scope")).andExpect(status().isOk()); 
  
          client.setScope("other_scope");
          Mockito.when(securityContext.getAuthentication()).thenReturn(createMockAuth(client));
          // NestedServletException thrown here
          mvc.perform(get("/api/scope")).andExpect(status().isForbidden()); 
      }
  }
  </code></pre>
  
  <p>The exception that is thrown is the following (which is expected):</p>
  
  <blockquote>
    <p>org.springframework.web.util.NestedServletException: Request
    processing failed; nested exception is
    org.springframework.security.access.AccessDeniedException:
    Insufficient scope for this resource</p>
  </blockquote>
  
  <p>My question is <strong>how can I prevent this exception from interfering with my test case?</strong></p>