0

I have a controller like this :

@ExtendWith(SpringExtension.class)
@RestController
@RequestMapping("/")
public class TestController {
    @GetMapping(value = "test")
    public String test() {
        return "Api running";
    }
}

I have the following test class:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = TestController.class)
@AutoConfigureMockMvc
public class TestControllerTest {
    private final String BASE_URL = "https://localhost:8080";
    @Autowired
    private MockMvc mockMvc;

    @Test
    public void shouldReturnOk() throws Exception{
        this.mockMvc.perform(get("/test"))
                .andExpect(status().isOk());
    }
}

My WebSecurityConfig http configuration looks like this:

@Override
protected void configure(HttpSecurity http) throws Exception {

// Disable CSRF (cross site request forgery)
http.csrf().disable();

// No session will be created or used by spring security
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

// Entry points
http.authorizeRequests()//
    .antMatchers("/users/signin").permitAll()//
    .antMatchers("/users/signup").permitAll()//
    .antMatchers("/h2-console/**/**").permitAll()
    .antMatchers("/test").permitAll()
    // Disallow everything else..
    .anyRequest().authenticated();

// If a user try to access a resource without having enough permissions
http.exceptionHandling().accessDeniedPage("/login");

// Apply JWT
http.apply(new JwtTokenFilterConfigurer(jwtTokenProvider));

// Optional, if you want to test the API from a browser
// http.httpBasic();
}

When I make an http call from postman the antMatcher works as it should:

response to call in postman

But when I run the test class I get the following response:

java.lang.AssertionError: Status 
Expected :200
Actual   :401
<Click to see difference>

I'm using intellij IDEA. My folder structure looks like this:

folder structure

It seems I need to configure the app separately in the tests, but I don't know how that's done.

How do I make my antmatcher allow the request through in the test?

UPDATE: Don't know if it matters but I've noticed that my request is going to a different port than the port I had my app running on:

MockHttpServletRequest:
      HTTP Method = GET
      Request URI = /test
       Parameters = {}
          Headers = {}
             Body = <no character encoding set>
    Session Attrs = {SPRING_SECURITY_SAVED_REQUEST=DefaultSavedRequest[https://localhost:8443/test]}

My app is running on :8080 but it's sending the request to ':8443`. It even does this if I hardcode the url like so: (FURTHER UPDATE: @SimonMartinelli pointed out this is because it's making an https call, so that is not the problem.)

this.mockMvc.perform(get(BASE_URL+ "/test"))

YET ANOTHER UPDATE: it seems it's almost certainly happening because my http.authorizeRequests() method isn't running. So how do I get it to authorize the requests?

Simon Martinelli
  • 34,053
  • 5
  • 48
  • 82
jimboweb
  • 4,362
  • 3
  • 22
  • 45
  • Can you please show your test class? – Simon Martinelli Nov 02 '19 at 18:58
  • @Simon I did. It's the second piece of code in the post. – jimboweb Nov 02 '19 at 19:10
  • Oh sorry. The base url in the test is https that's probably why it calls 8443 – Simon Martinelli Nov 02 '19 at 19:20
  • Oh, you're right. I changed it to http and it called 8080. Still gets 401 response but that at least explains that. – jimboweb Nov 02 '19 at 19:27
  • What if you remove the class attribute from SprinBootTest? – Simon Martinelli Nov 02 '19 at 19:45
  • A few other things: Which version of Spring Boot are you using? And @ExtendWith(SpringExtension.class) doesn't make sense on TestController – Simon Martinelli Nov 03 '19 at 10:06
  • @SimonMartinelli when I remove the class from SpringBootTest I get this error: java.lang.IllegalStateException: Unable to find SpringBootConfiguration, you need to use ContextConfiguration or SpringBootTest(classes=...) with your test – jimboweb Nov 03 '19 at 11:56
  • I'm using Spring 2.1.0. And you're right, I don't know why I had that ExtendWith on the controller. – jimboweb Nov 03 '19 at 12:00
  • You're right, it is a duplicate of that comment. According to the GitHub issue mentioned there the tests don't configure security by default, which is kind of crazy because who doesn't use security? But that solved my problem. Recommend this question be closed as duplicate. – jimboweb Nov 03 '19 at 12:23
  • It configures security by default but does not take your configuration unless you define it explicitly – Simon Martinelli Nov 03 '19 at 14:21

0 Answers0