Spring mock mvc test return 404 @withmockuser

Viewed 354

When i don't use @WithMockUser return status 401 but when i use @WithMockUser return status code 404

My Contoller

@RestController
@RequestMapping("/api/stocks")
@Api(tags = "stocks")
@Slf4j
public class StockResource {

  @GetMapping("/test/test")
  @Secured("SYS_ADMIN")
  public @ResponseBody String getTest() {
      return "hello";
  }}

My Test

@SpringBootTest
@EnableAutoConfiguration(exclude = {LiquibaseAutoConfiguration.class})
@AutoConfigureMockMvc
@ContextConfiguration
class RonadTestApplicationTests {

    @Autowired
    private MockMvc mvc;

    @Test
    @WithMockUser(authorities = {"SYS_ADMIN"})
    void contextLoads() throws Exception {
        mvc.perform(get("/api/stocks/test/test")
                .contentType("application/json"))
                .andExpect(status().isOk());
    }

}

and my output when i dont use @WithMockUser

Status expected:<200> but was:<401>
Expected :200
Actual   :401

and my output when i use @WithMockUser

Status expected:<200> but was:<404>
Expected :200
Actual   :404
1 Answers

It looks like you are trying to test the role-based access, but in the annotation you are specifiying an authority. Since @Secured() annotation specifies a role that should be granted access, not an authority (more on that here https://www.baeldung.com/spring-security-method-security).
Try using @WithMockuser(roles = "SYS_ADMIN") instead

 @Test
    @WithMockUser(roles = {"SYS_ADMIN"})   //<===== here
    void contextLoads() throws Exception {
        mvc.perform(get("/api/stocks/test/test")
                .contentType("application/json"))
                .andExpect(status().isOk());
    } 
Related