我有一个像这样的控制器,这似乎是Spring启动的一个问题 没有人能够解决这个问题,另一个用户提出了同样的问题,请查看链接Error when using @WebMvcTest annotation on a Spring Boot test class
@Controller
@RequestMapping("/book")
public class BookController {
@RequestMapping(value = "/add", method = RequestMethod.POST)
public String addBookPost(@ModelAttribute("book") Book book, HttpServletRequest request, Model model) {
bookService.save(book);
MultipartFile bookImage = book.getBookImage();
try {//do something
}
return "redirect:bookList";
}
这是我使用@WebMvcTest生成的测试
@AutoConfigureMockMvc(secure = false)
@RunWith(SpringRunner.class)
@WebMvcTest(controllers = {BookController.class}, includeFilters = @ComponentScan.Filter(classes = EnableWebSecurity.class))
public class BookControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private BookService bookService;
@Test
@WithMockUser(username = "admin", authorities = {"ADMIN"})
public void addBookClicked() throws Exception {
this.mockMvc.perform(post("/book/add")
.accept(MediaType.TEXT_HTML)
.contentType(MediaType.TEXT_HTML)).andExpect(status().isOk())
.andExpect(model().attributeExists("book"))
.andExpect(view().name("addBook"))
.andReturn();
}
这是从app.properties
导入bean的配置 @Configuration
@Import({PropertyTestConfiguration.class, SecurityUtility.class})
static class ContextConfiguration {
}
我收到此错误
MockHttpServletRequest:
HTTP Method = POST
Request URI = /book/add
Parameters = {}
Headers = {}
java.lang.AssertionError: Range for response status value 404
Expected :REDIRECTION
Actual :CLIENT_ERROR
<Click to see difference>
at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:54)
at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:81)
at org.springframework.test.web.servlet.result.StatusResultMatchers$5.match(StatusResultMatchers.java:107)
at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:171)
at com.valentine.adminportal.controller.BookControllerTest.TestWithoutAuthentication(BookControllerTest.java:48)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke
请注意,当测试通过使用@SpringBootTest时,此测试通过,任何帮助就足够了。谢谢,我使用了springio和其他网站的引用,我的测试基本相同,所以我不知道我的错误来自哪里。