How to test spring configuration classes?

You should be able to test the configuration using the @ContextConfiguration annotation. For Example, the SecurityConfiguration class can be tested like this:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SecurityConfiguration.class) 
class SecurityConfigurationTest {

    @Autowired
    SecurityConfiguration securityConfiguration;

    @Test
    public void passwordEncoderTest() throws Exception {
        final BCryptPasswordEncoder encoder = securityConfiguration.passwordEncoder();
        final String encodedPassword = encoder.encode("password");
        assertNotNull(encodedPassword);
    }
}

I believe this can only be achieved with an Integration Test.

The purpose of Unit Tests are not to check if the whole Spring Context is being created successfully.

You can test each configuration method with a Unit Test by using mocks, etc to check if they are OK, but the whole Spring Context thing is an Integration test.

I use to do this Configuration Test by doing what Spring Docs calls "Spring Unit Test" (that for me is more like a Integration Test of the Controllers + Views)

The idea is that, if you can get a Spring Context running for a Controller integration Test, then your Configurations are OK.

There is a whole chapter in spring docs on how to do that kind of test. http://docs.spring.io/spring/docs/current/spring-framework-reference/html/testing.html


In a word - "don't", that way lays madness.

What you really want is higher level tests that make use of your Spring configuration but are still focused on behaviour not implementation.

For example, looking at your security configuration - you don't really care that the configure method is called, or what it does, what you want to test for is:

  1. Static pages don't require authentication
  2. Other pages do require authentication
  3. Logging in works
  4. Logging out works

Using Spring for DI and security is merely how those things are implemented whereas your tests should be focused on the fact those things actually work.


You could build the context in a JUnit test, provided that all the beans can be instantiated in the test environment. You can use AnnotationConfigApplicationContext and its scan() method to do this.

Such test should be enough for a quick verification of the config. And you can go from there, obtaining beans from the context for a more complex testing.

Couple of pitfalls:

  • Might not work well for lazy-initialized beans
    • You may need to actually request an instance from the context using getBean() for such a class to ensure it is created - you can test that expectation this way
  • May not be always possible, e.g. if you have some database connection as a dependency and don't have access to the database in the test environment
    • You may need to mock such beans for the test's purposes