Spring Mvc 集成测试失败

Spring Mvc integration test fails

我想为我的控制器中的删除方法编写集成测试,但无论我尝试重写多少次,我仍然会遇到不同的错误。 这是我控制器中的方法:

@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:/";
    }
}

这是测试,简单明了,只是调用方法并检查状态:

@SpringBootTest
@TestPropertySource(locations = "classpath:application-h2.properties")
@AutoConfigureMockMvc
@WithMockUser(username = "user1@gmail.com")
@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());
    }
}

这是我得到的:

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 [Username=user1@gmail.com, 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

我做错了什么?对我来说这似乎是一个简单的测试,但我显然遗漏了一些东西。

集成测试工作正常。例如,“home”return 值为呈现的模板提供 HTTP 200 Ok 状态。此处,重定向导致 HTTP 302 Found 状态。此响应告诉客户端(浏览器)资源已(暂时)移动。

将测试更改为 .andExpect(status().isFound()) 将使其成功。