0

I have API endpoints which require a user to hold a specific role. Therefore, in some of my tests I attempt to reach these endpoints and expect a 401 error, however I get 200. I am using MockMvc to perform the calls.

The following are some snippets of the controller class with one of the methods that I am testing:

@RestController
public class MyController {


    @GetMapping("/getcurrentuser")
    public User getCurrent() {
         ...code
    }

}

The following is my test class (only showing the respective test method and variables):

@RunWith(SpringRunner.class)
@WebMvcTest(MyController.class)
@ContextConfiguration(classes = MyController.class)
public class MyControllerTest {

    @Autowired
    private MockMvc mockMvc;
@Test
    public void testGetCurrentFailedDueToIncorrectRole() throws Exception {
        mockMvc.perform(get("/api/getcurrentuser")
                        .with(user(USER_NAME).password(PASSWORD)))
               .andExpect(status().isUnauthorized());
    }
}

I have also have a spring security config class, however I'm not sure if it's being brought into context in this test (sorry I'm still fairly new to spring and unit testing). Inside this class I have the following line of code:

.antMatchers("/api/**").hasAnyRole("ADMIN", "READ_ONLY")

The test showed previously fails, as I said I get 200. Now at this point I think that I'm doing something wrong in the configuration of this test and that is why roles are not being accounted for. Or maybe I am confused on how the ".with" part works.

Any form of help would be appreciated.

D. Gal
  • 329
  • 2
  • 14
  • @WebMvcTest don't use your Configuration classes. That's mean what your security config will not be use. But i think your problem not is this. – Alexander Polozov Jul 13 '18 at 16:22

1 Answers1

0

If you are using Spring Boot, you might want to try using @SpringBootTest and @AutoConfigureMockMvc.

Jeff
  • 45
  • 2
  • 8