0

I'm a newer of Spring MVC , and I'm trying to config a simple controller like below ,but when i test it. I got

javax.servlet.ServletException: Circular view path [index]: would dispatch back to the current handler URL [/index] again. Check your ViewResolver setup! (Hint: This may be the result of an unspecified view, due to default view name generation.)

Here is my WebConfig.java Code:

 @Bean
public ViewResolver viewResolver() {

    InternalResourceViewResolver resolver = new InternalResourceViewResolver();
    resolver.setPrefix("/WEB-INF/views/");
    resolver.setSuffix(".jsp");

    return resolver;
}

Here is my IndexController.java Code:

@Controller
@RequestMapping("/index")

public class IndexController {

@RequestMapping(method = RequestMethod.GET)
public String index() {

    return "index";
}

}

Here is my Test Fiel :

public class TestIndexController {

  @Test
  public void testIndexController() throws Exception {

    IndexController indexController = new IndexController();

    MockMvc mockMvc = standaloneSetup(indexController).build();

    mockMvc.perform(get("/index")).andExpect(view().name("index"));
 }

}

Every time when i changed the get("/index") to get("/index.jsp") ,i passed the test. but i just can't figure it out, please help me out

jny
  • 8,007
  • 3
  • 37
  • 56
  • Possible duplicate of [How to avoid the "Circular view path" exception with Spring MVC test](http://stackoverflow.com/questions/18813615/how-to-avoid-the-circular-view-path-exception-with-spring-mvc-test) – jny Oct 12 '16 at 13:15

1 Answers1

0

In your test setup, you create an instance of the Controller under test, but the context created for the test has no knowledge of the existence of your WebConfig and therefore, no instance of your ViewResolver.

Here is a quick fix :

public void testIndexController() throws Exception {
  IndexController indexController = new IndexController();
  MockMvc mockMvc = standaloneSetup(indexController)
                    setViewResolvers((new WebConfig()).viewResolver()).build();
  mockMvc.perform(get("/index")).andExpect(view().name("index"));
}

If you don't want to access WebConfig in your test class, you can also create a new instance of ViewResolver and add it to your mockMvc setup.

Hope this helps.

Akshay
  • 3,158
  • 24
  • 28