Search code examples
spring-bootjunitjunit5spring-restcontroller

Junit rest controller throws login url instead of Actual model and view


I am tring to test my spring-boot rest controller, its giving the login page instead of actual result. its giving 302 status, I have given the controller code , test case and error given by the junit.Please have look all the code and let me you need any other information

Controller

@GetMapping("{userId}/edit/{todoId}")
public ModelAndView updateTodo(@PathVariable Long userId, @PathVariable Long todoId) {
    
    User user = userService.findById(userId);
    ModelAndView model = new ModelAndView("todo-form.jsp");
    model.addObject("userId",userId);
    return model;
}

Junit test

@ExtendWith(SpringExtension.class)
@SpringBootTest
@AutoConfigureMockMvc
class UserApiControllerTest {

@DisplayName("Test updateTodo Api")
@Test
public void updateTodo() throws Exception {
    
    mockMvc.perform(get("/1/edit/2"))
    .andExpect(status().isOk());
     
}

ERROR

MockHttpServletRequest:
          HTTP Method = GET
          Request URI = /1/edit/2
           Parameters = {}
              Headers = []
                 Body = null
        Session Attrs = {SPRING_SECURITY_SAVED_REQUEST=DefaultSavedRequest[http://localhost/1/edit/2]}
    Handler:
                 Type = null
    Async:
        Async started = false
         Async result = null
    Resolved Exception:
                 Type = null
    ModelAndView:
            View name = null
                 View = null
                Model = null
    FlashMap:
           Attributes = null
    MockHttpServletResponse:
               Status = 302
        Error message = null
               Expires:"0", Location:"http://localhost/login"]
     Content type = null
     Body = 
     Forwarded URL = null
     Redirected URL = http://localhost/login

Solution

  • Try disabling spring security as it's redirecting to login page.

    @AutoConfigureMockMvc(addFilters = false)
    

    secure=false should work too but may be deprecated depending on your version of Spring