While running a Standalone Junit Test for Spring Controller, sometimes you may incur the below exception, and your test will fail. This is because, when you don't declare or configure the ViewResolver in UnitTest, Spring registers a default InternalResourceViewResolver which creates instances of JstlView for rendering the View.
To resolve the issue, we need to configure the ViewResolver, in the setup method of the Test class, Below is the sample code to do that. In the setup method, i have initialized the InternalResourceViewResolver, and assigned it to the viewResolver of standaloneSetup of MockMvcBuilder, this will resolve the issue.
Happy Programming.
javax.servlet.ServletException: Circular view path [addExpense]: would dispatch back to the current handler URL [/addExpense] again. Check your ViewResolver setup! (Hint: This may be the result of an unspecified view, due to default view name generation.) at org.springframework.web.servlet.view.InternalResourceView.prepareForRendering(InternalResourceView.java:292) at org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:214) at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:263) at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1208)
To resolve the issue, we need to configure the ViewResolver, in the setup method of the Test class, Below is the sample code to do that. In the setup method, i have initialized the InternalResourceViewResolver, and assigned it to the viewResolver of standaloneSetup of MockMvcBuilder, this will resolve the issue.
public class ExpenseControllerTest { @InjectMocks private ExpenseController expenseController; private MockMvc mockMvc; @Before public void setup() { // Process mock annotations MockitoAnnotations.initMocks(this); // Setup Spring test in standalone mode InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); viewResolver.setPrefix("/WEB-INF/jsp"); viewResolver.setSuffix(".jsp"); this.mockMvc = MockMvcBuilders.standaloneSetup(expenseController).setViewResolvers(viewResolver).build(); } @Test public void testAddExpense() throws Exception{ mockMvc.perform(get("/addExpense")) .andExpect(status().isBadRequest()) .andExpect(view().name("addExpense")); } }
Happy Programming.