Unit testing controllers with CSRF protection enabled in Spring security

The way to solve this issue is : import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.*; … @Test public void testLogin() throws Exception { this.mockMvc.perform(post(“/login”) .param(“username”, “…”) .param(“password”, “…”) .with(csrf())) .andExpect(status().isFound()) .andExpect(header().string(“Location”, “redirect-url-on-success-login”)); } The important part is : .with(csrf()) which will add the expected _csrf parameter to the query. The csrf() static method is provided by spring-security-test : <dependency> … Read more

Isolated Controller Test can’t instantiate Pageable

Original answer: The problem with pageable can be solved by providing a custom argument handler. If this is set you will run in a ViewResolver Exception (loop). To avoid this you have to set a ViewResolver (an anonymous JSON ViewResolver class for example). mockMvc = MockMvcBuilders.standaloneSetup(controller) .setCustomArgumentResolvers(new PageableHandlerMethodArgumentResolver()) .setViewResolvers(new ViewResolver() { @Override public View resolveViewName(String … Read more

Failed to load ApplicationContext for JUnit test of Spring controller

As mentioned in the discussion: WEB-INF is not really part of the class path. If you use a common template, such as maven, use src/main/resources or src/test/resources to place the app-context.xml in. Then you can use classpath:. Place your config file in src/main/resources/app-context.xml and use the following code: @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = “classpath:app-context.xml”) public class PersonControllerTest … Read more

How to avoid the “Circular view path” exception with Spring MVC test

@Controller → @RestController I had the same issue and I noticed that my controller was also annotated with @Controller. Replacing it with @RestController solved the issue. Here is the explanation from 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 … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)