Java 当请求Url和视图名称相同时进行mockmvc测试
测试控制器:Java 当请求Url和视图名称相同时进行mockmvc测试,java,spring,mockmvc,Java,Spring,Mockmvc,测试控制器: @Controller @RequestMapping("/test") public class TestController { @RequestMapping(method = GET) public void test(Model model) { } } JunitTest: import static org.springframework.test.web.servlet.request.MockMvcRequestBuild
@Controller
@RequestMapping("/test")
public class TestController {
@RequestMapping(method = GET)
public void test(Model model) {
}
}
JunitTest:
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.*;
import org.junit.Test;
import org.springframework.test.web.servlet.MockMvc;
public class Test2 {
@Test
public void testPage() throws Exception {
TestController controller = new TestController();
MockMvc mockMvc = standaloneSetup(controller).build();//.setSingleView(new InternalResourceView("/WEB-INF/views/test.jsp"))
mockMvc.perform(get("/test"))
.andExpect(view().name("test"));
}
}
运行JunitTest,出现异常:
javax.servlet.ServletException: Circular view path [test]: would dispatch back to the current handler URL [/test] again. Check your ViewResolver setup! (Hint: This may be the result of an unspecified view, due to default view name generation.)
我知道我可以使用setSingleView,但我检查了StandaloneMockMvcBuilder的api
public StandaloneMockMvcBuilder setViewResolvers(ViewResolver... resolvers)
Set up view resolution with the given ViewResolvers. If not set, an InternalResourceViewResolver is used by default.
这意味着使用了InternalResourceViewResolver,所以servlet将分派到“test.jsp”而不是“/test”,它不应该是一个圆,并且在我在浏览器中进行测试时工作良好。或者StandaloneMockMvcBuilder不使用任何视图解析器?您需要返回一个字符串,该字符串将作为视图的名称(在控制器方法中)@TiarêBalbi I在控制器方法中添加了“return”test,但例外情况是相同的