gpt4 book ai didi

spring - 如何使用 Spring MVC 测试避免 "Circular view path"异常

转载 作者:IT老高 更新时间:2023-10-28 13:01:16 30 4
gpt4 key购买 nike

我的一个 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-annotatedwith @Controller and @ResponseBody indicating a controller whose everymethod inherits the type-level @ResponseBody annotation and thereforewrites directly to the response body vs view resolution and renderingwith an HTML template.

关于spring - 如何使用 Spring MVC 测试避免 "Circular view path"异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18813615/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com