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

标签 spring spring-mvc circular-reference thymeleaf spring-mvc-test

我的一个 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/

相关文章:

Spring ApplicationListener在webapp上被触发了两次

java - 将 h2 数据库实现到现有的 spring-boot 应用程序

java - 如何将复杂对象从 Controller 传递到 View (jsp)

java - spring-batch-integration 1.2.2 与 spring-batch 2.2.2 不兼容

java - 使用 Spring 3.1 使用外部 Web 服务

java - 为持久性单元 'default' 关闭 JPA Entity_Manage_Factory

Spring OpenentityManagerInViewFilter 替代品

immutability - Kotlin 中带有 val 的循环引用

c# - Visual Studio for Mac : Logs work on a Project and are shown on Azure, 但在同一解决方案的另一个项目上失败

c# - 如何彻底解决IoC循环引用?