'Spring Mvc integration test fails

I want to write an integration test for a delete method in my controller, but no matter how many times I tried rewriting it, I am still getting different errors. This is the method in my controller:

@Controller
public class AgencyController {

    @Autowired
    private AgencyService agencyService;

    @Autowired
    private AgencyMapper agencyMapper;
@GetMapping("/deleteAgencyPage/{id}")
    public String deleteAgencyPage(@PathVariable(value = "id") Long id) {
        agencyService.deleteById(id);
        return "redirect:/";
    }
}

And this is the test, plain and simple, only a call to the method and checking a status:

@SpringBootTest
@TestPropertySource(locations = "classpath:application-h2.properties")
@AutoConfigureMockMvc
@WithMockUser(username = "[email protected]")
@ActiveProfiles("H2")
public class AgencyControllerTest {
    @Autowired
    MockMvc mockMvc;

    @MockBean
    AgencyService agencyService;

    @MockBean
    AgencyMapper agencyMapper;

    @MockBean
    Model model;

 @Test
    public void deleteAgency() throws Exception {
        mockMvc.perform(get("/deleteAgencyPage/{id}",1L))
                .andExpect(status().isOk());
    }
}

This is what I get:

MockHttpServletRequest:
      HTTP Method = GET
      Request URI = /deleteAgencyPage/1
       Parameters = {}
          Headers = []
             Body = <no character encoding set>
    Session Attrs = {SPRING_SECURITY_CONTEXT=SecurityContextImpl [Authentication=UsernamePasswordAuthenticationToken [Principal=org.springframework.security.core.userdetails.User [[email protected], Password=[PROTECTED], Enabled=true, AccountNonExpired=true, credentialsNonExpired=true, AccountNonLocked=true, Granted Authorities=[ROLE_USER]], Credentials=[PROTECTED], Authenticated=true, Details=null, Granted Authorities=[ROLE_USER]]]}

Handler:
             Type = com.example.awbdproject.controllers.AgencyController
           Method = com.example.awbdproject.controllers.AgencyController#deleteAgencyPage(Long)

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = null

ModelAndView:
        View name = redirect:/
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 302
    Error message = null
          Headers = [Content-Language:"en", X-Content-Type-Options:"nosniff", X-XSS-Protection:"1; mode=block", Cache-Control:"no-cache, no-store, max-age=0, must-revalidate", Pragma:"no-cache", Expires:"0", X-Frame-Options:"DENY", Location:"/"]
     Content type = null
             Body = 
    Forwarded URL = null
   Redirected URL = /
          Cookies = []

java.lang.AssertionError: Status expected:<200> but was:<302>
Expected :200
Actual   :302

What am I not doing correct? It seems a simple test to me, but I am obviously missing something.



Solution 1:[1]

The integration test works correctly. For example, a "home" return value serves your rendered template with a HTTP 200 Ok status. Here, a redirect leads to a HTTP 302 Found status. This response tells the client (browser) that the resource has (temporarily) moved.

Changing the test to .andExpect(status().isFound()) would make it succeed.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Matthias