Disable security for unit tests with spring boot
In my case, @AutoConfigureMockMvc(addFilters = false)
helped me.
Example:
@WebMvcTest(MyController.class)
@AutoConfigureMockMvc(addFilters = false)
@TestPropertySource(locations="classpath:application-test.properties")
public class MyControllerTests {
Cheers
UPDATE to ANSWER: Another option i recently learned if I am using MockMvc and AutoConfigureMockMvc to test my controllers, i can just set secure=false on it to disable any security applicable to your controllers.
@AutoConfigureMockMvc(secure = false)
If not go with below for basic auth.
The exception you get is very different than what i was getting but if you want to disable the security while running test cases, you can trying using profiles and disabling the basic security using properties for test profile. This is what i did -
- Added annotation
@Profile(value = {"development", "production"})
to my implementation ofWebSecurityConfigurerAdapter
-
@Configuration
@EnableWebSecurity
@Profile(value = {"development", "production"})
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
2. Now, in test/resources
, create application-test.yml
to define properties for test profile and add this -
# Security enable/disable
security:
basic:
enabled: false
3. Now, to your test cases, add this annotation to apply the active profile @ActiveProfiles(value = "test")
. This is how my class looked -
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@WebAppConfiguration
@ActiveProfiles(value = "test")
@IntegrationTest({"server.port=0"})
public class SampleControllerIntegrationTest {
Doing this disabled the security for my test cases and i was able to access the authenticated urls. I hope this works for you too. Best of luck!!!
FmpdfApplication
is likely annotated with @EnableAutoConfiguration
(or with @SpringBootApplication
which is meta-annotated with @EnableAutoConfiguration
), and this will lead to Spring Security being picked up and configured via auto-configuration.
If you want to see what's being auto-configured, launch your web app and access the autoconfig
endpoint (e.g., http://localhost:8080/autoconfig). Then search for 'Security' to see which 'AutoConfiguration' classes are being detected.
You can then disable auto-configuration of security by excluding those classes like this:
@EnableAutoConfiguration(exclude = { SecurityAutoConfiguration.class, ManagementSecurityAutoConfiguration.class })
Of course, you won't want to exclude them for production deployments. Thus you'll need to have a separate @Configuration
class for production and tests.
Regards,
Sam
p.s. You might also find my answer to the following question useful as well: Spring-Boot module based integration testing