I have the following code in one of my controllers:
@Controller
@RequestMapping("/preference")
public class PreferenceController {
@RequestMapping(method = RequestMethod.GET, produces = "text/html")
public String preference() {
return "preference";
}
}
I am simply trying to test it using Spring MVC test as follows:
@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());
}
}
I am getting the following exception:
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.)
What I find strange is that it works fine when I load the "full" context configuration that includes the template and view resolvers as shown below:
<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>
I am well aware that the prefix added by the template resolver ensures that there are not "circular view path" when the app uses this template resolver.
But then how I am supposed to test my app using Spring MVC test? Has anyone got any clue?
I solved this problem by using @ResponseBody like below:
I am using Spring Boot with Thymeleaf. This is what worked for me. There are similar answers with JSP but note that I am using HTML, not JSP, and these are in the folder
src/main/resources/templates
like in a standard Spring Boot project as explained here. This could also be your case.Hope this helps.
Here's an easy fix if you don't actually care about rendering the view.
Create a subclass of InternalResourceViewResolver which doesn't check for circular view paths:
Then set up your test with it:
Another simple approach:
I am using Spring Boot to try and load a webpage, not test, and had this problem. My solution was a bit different than those above considering the slightly different circumstances. (although those answers helpled me understand.)
I simply had to change my Spring Boot starter dependency in Maven from:
to:
Just changing the 'web' to 'thymeleaf' fixed the problem for me.
If you are using Spring Boot, then add thymeleaf dependency into your pom.xml: