我的一个 Controller 中有以下代码:
@Controller
@RequestMapping("/preference")
public class PreferenceController {
@RequestMapping(method = RequestMethod.GET, produces = "text/html")
public String preference() {
return "preference";
}
}
我只是尝试使用 Spring MVC 测试 来测试它,如下所示:
@ContextConfiguration
@WebAppConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
public class PreferenceControllerTest {
@Autowired
private WebApplicationContext ctx;
private MockMvc mockMvc;
@Before
public void setup() {
mockMvc = webAppContextSetup(ctx).build();
}
@Test
public void circularViewPathIssue() throws Exception {
mockMvc.perform(get("/preference"))
.andDo(print());
}
}
我收到以下异常:
Circular view path [preference]: would dispatch back to the current handler URL [/preference] again. Check your ViewResolver setup! (Hint: This may be the result of an unspecified view, due to default view name generation.)
我觉得奇怪的是 当我加载包含模板和 View 解析器的“完整”上下文配置时它工作正常,如下所示:
<bean class="org.thymeleaf.templateresolver.ServletContextTemplateResolver" id="webTemplateResolver">
<property name="prefix" value="WEB-INF/web-templates/" />
<property name="suffix" value=".html" />
<property name="templateMode" value="HTML5" />
<property name="characterEncoding" value="UTF-8" />
<property name="order" value="2" />
<property name="cacheable" value="false" />
</bean>
我很清楚,模板解析器添加的前缀可确保应用使用此模板解析器时不存在“圆形 View 路径”。
那么我应该如何使用 Spring MVC 测试来测试我的应用程序呢?
最佳答案
@Controller
→ @RestController
我遇到了同样的问题,我注意到我的 Controller 也用 @Controller
进行了注释。用 @RestController
替换它解决了这个问题。这是来自 Spring Web MVC 的解释:
@RestController is a composed annotation that is itself meta-annotated with @Controller and @ResponseBody indicating a controller whose every method inherits the type-level @ResponseBody annotation and therefore writes directly to the response body vs view resolution and rendering with an HTML template.
关于spring - 如何使用 Spring MVC 测试避免 "Circular view path"异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18813615/