我想在我的控制器中为一个delete方法编写一个集成测试,但是不管我尝试了多少次重写它,我仍然会遇到不同的错误。这是我的控制器中的方法:
@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
我做错什么了?对我来说,这似乎是一个简单的测试,但我显然遗漏了一些东西。
发布于 2022-04-22 14:31:23
集成测试工作正常。例如,"home“返回值为您呈现的模板提供HTTP 200 Ok状态。在这里,重定向会导致HTTP 302找到状态。此响应通知客户端(浏览器)资源已(临时)移动。
将测试更改为.andExpect(status().isFound())
将使其成功。
https://stackoverflow.com/questions/71797633
复制相似问题