How to associate the mockmvc user to the security context holder

21 Views Asked by At

I am having trouble with not being able to associate the user I am passing into the mockmvc get request to the security context holder so I am able to create a mock principle.

@Import(SecurityConfig::class)
@WebMvcTest(controllers = [MovieController::class])
class MovieControllerTests {
    private lateinit var mockMvc: MockMvc

    @MockBean
    private lateinit var accountRepository: AccountRepository

    @MockBean
    private lateinit var movieRepository: MovieRepository

    @BeforeEach
    fun setup() {
        mockMvc = MockMvcBuilders.standaloneSetup(MovieController(movieRepository, accountRepository))
            .apply<StandaloneMockMvcBuilder?>(SecurityMockMvcConfigurers.springSecurity()).build()
    }
    @Test
    fun `does return movie queue`() {
        mockMvc.get("/movies/fetch-queue") {
            with(user("donna"))
        }.andExpectAll {
            status {
                isOk()
            }
            content {
                contentType(MediaType.APPLICATION_JSON)
            }
        }
        Mockito.verify(accountRepository).findAccountByUsername("donna")
    }
}

I have read the documentation that says I need to manually add the securitycontextpersistencefilter to the mockmvc instance, however I don't know how exactly to do that. The documentation also says that mocking users only works by associating the user with the HttpServletRequest.

0

There are 0 best solutions below