pact-foundation / pact-jvm

JVM version of Pact. Enables consumer driven contract testing, providing a mock service and DSL for the consumer project, and interaction playback and verification for the service provider project.
https://docs.pact.io
Apache License 2.0
1.08k stars 480 forks source link

spring security in unit tests #472

Open arashbi opened 7 years ago

arashbi commented 7 years ago

I want to test my secure end-points using spring module, but I cannot find a way to bootstrap spring security. Ideally, I would like to have a Principal object injected to my controller method. I can do it easily if I was writing the test, simply add it to the mockMvc method call. The question is : how to bootstrap Spring in Pact easily.

nieldw commented 6 years ago

547 might help a bit, but even then I don't yet see a way to set a mock user the way you would on MockMvc.

viktorgt commented 6 years ago

You can setup your own instance of MockMvc (https://docs.spring.io/spring-security/site/docs/current/reference/html/test-mockmvc.html) and pass it to the MockMvcTarget. This is how we setup the Pact Provider tests with secured endpoints:

    public MockMvcTarget mockMvcTarget(@Value("${server.servlet.context-path}") String contextPath,
                                       WebApplicationContext webApplicationContext) {
        var requestBuilder = MockMvcRequestBuilders.get("/")
                .servletPath(contextPath)
                .with(user("admin")
                        .password("pass")
                        .roles("supervisor", "operator"));
        MockMvc mockMvc = MockMvcBuilders
                .webAppContextSetup(webApplicationContext)
                .defaultRequest(requestBuilder)
                .apply(springSecurity())
                .build();

        MockMvcTarget mockMvcTarget = new MockMvcTarget();
        mockMvcTarget.setMockMvc(mockMvc);

        return mockMvcTarget;
    }
AlistratenkoNikita commented 2 years ago

@arashbi Hey, have you figured out how to set up the Authentication object for the controllers? I am currently stuck on this :(