我是Spring MVC的新手,我正在尝试配置如下的简单控制器,但是当我测试它时。我得到了
javax.servlet.ServletException: Circular view path [index]: would dispatch back to the current handler URL [/index] again. Check your ViewResolver setup! (Hint: This may be the result of an unspecified view, due to default view name generation.)
这是我的WebConfig.java代码:
@Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
}
这是我的IndexController.java代码:
@Controller
@RequestMapping("/index")
public class IndexController {
@RequestMapping(method = RequestMethod.GET)
public String index() {
return "index";
}
}
这是我的Test Fiel:
public class TestIndexController {
@Test
public void testIndexController() throws Exception {
IndexController indexController = new IndexController();
MockMvc mockMvc = standaloneSetup(indexController).build();
mockMvc.perform(get("/index")).andExpect(view().name("index"));
}
}
每当我将get(“/ index”)更改为get(“/ index.jsp”)时,我都通过了测试。但我无法理解,请帮帮我
答案 0 :(得分:0)
在您的测试设置中,您创建了一个正在测试的Controller
的实例,但为测试创建的上下文并不知道您的WebConfig
是否存在,因此,没有您{的实例{1}}。
这是一个快速修复:
ViewResolver
如果您不想在测试类中访问public void testIndexController() throws Exception {
IndexController indexController = new IndexController();
MockMvc mockMvc = standaloneSetup(indexController)
setViewResolvers((new WebConfig()).viewResolver()).build();
mockMvc.perform(get("/index")).andExpect(view().name("index"));
}
,还可以创建WebConfig
的新实例并将其添加到ViewResolver
设置中。
希望这有帮助。