Is it possible to create unit tests for Spring security intercepted addresses

Our application has url filtering using spring security as in:

<intercept-url pattern="/resources/**" access="ROLE_ANONYMOUS,ROLE_USER"/>

      

We would like to write a unit test that takes a Url list and checks for each method (GET, POST, PUT ..) if available.

I looked at using DelegatingFilterProxy

it but didn't know how to load config/context

into ours web.xml

.

Is this a valid approach or is something advisable?

+3


source to share


2 answers


You can create tests to intercept URLs using @Autowire DelegatingFilterProxy and use MockHttpServletRequest, MockHttpServletResponse and MockFilterChain to test the result.



If you are using Spring MVC you can take a look at Spring Test MVC which supports filters (including Spring Security). You can find a sample in the repository . Please note that Spring Test MVC is included in Spring 3.2+ (in the spring-test module). It is also available as a plug-in for Spring 3.1.

0


source


My tests involve intercept-url:



@ContextConfiguration({
        "classpath:spring/spring-app.xml",
         ...
})
@WebAppConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@Transactional
public class ControllerTest {

    private static final CharacterEncodingFilter CHARACTER_ENCODING_FILTER = new CharacterEncodingFilter();

    static {
        CHARACTER_ENCODING_FILTER.setEncoding("UTF-8");
        CHARACTER_ENCODING_FILTER.setForceEncoding(true);
    }

    protected MockMvc mockMvc;

    @Autowired
    private WebApplicationContext webApplicationContext;

    @PostConstruct
    private void postConstruct() {
        mockMvc = MockMvcBuilders
            .webAppContextSetup(webApplicationContext)
            .addFilter(CHARACTER_ENCODING_FILTER)
            .apply(springSecurity())
            .build();
    }

    @Test
    public void testUsers() throws Exception {
        mockMvc.perform(get("/users")
            .with(authentication(new UsernamePasswordAuthenticationToken("user", "password")))
            .andDo(print())
            .andExpect(status().isOk())
            .andExpect(view().name("users"))
            .andExpect(forwardedUrl("/WEB-INF/jsp/users.jsp"));
    }
    ...

      

0


source







All Articles