Skip to content
Advertisement

How can I use @WithMockUser and pass my username and password from my properties file?

I am writing an integration test where the application has a basic auth applied with spring security. I am using @WithMockUser to tell mockMVC how to authenticate with my endpoints.

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
@WithMockUser(username="username", password="password")

This works but I am wondering if I can replace those strings with references to the values in my application.properties file similiar how you can do:

    @Value("${spring.security.user.name}")
    private String userName;

Is the above possible?

Advertisement

Answer

I ended up removing the @WithMockUser annotation and went with this solution which worked better for my use case. This method authenticates with the configured basic auth so going forward if it was to change it wouldn’t be a problem.

@RunWith(SpringRunner.class)
@SpringBootTest
public class sampleTestIT {

    @Autowired
    private WebApplicationContext webApplicationContext;

    private MockMvc mockMvc;

    @Before
    public void setUp() throws Exception {
        mockMvc = webAppContextSetup(webApplicationContext).build();
    }
    ....
}

Advertisement