Home > OS >  How to test @Configuration class in Spring without starting up whole context?
How to test @Configuration class in Spring without starting up whole context?

Time:12-16

How can I test my configuration without starting the whole Spring context class or should I do that?

@Configuration
public class GaRuConfig {

    @Bean
    public List<GaRu> rules(){
        SSRule rule1 = new SSRule();
        CSRule rule2 = new CSRule();
        DGRule rule3 = new DGRule();
        EGRule rule4 = new EGRule();

        return List.of(rule1, rule2, rule3, rule4);
    }
}

Is there a way to test this class?

CodePudding user response:

Using AssertJ you can do the following:

public class GaRuConfigTest {

    private GaRuConfig gaRuConfig = new GaRuConfig();

    @Test
    public void shouldReturnCorrectListOfRulesWhenRequested() {
        // Act
        List<GaRu> rules = this.gaRuConfig.rules();

        // Assert
        Assertions.assertThat(rules.stream().filter(rule -> SSRule.class == rule.getClass()).collect(Collectors.toList())).isNotEmpty();
        Assertions.assertThat(rules.stream().filter(rule -> CSRule.class == rule.getClass()).collect(Collectors.toList())).isNotEmpty();
        Assertions.assertThat(rules.stream().filter(rule -> DGRule.class == rule.getClass()).collect(Collectors.toList())).isNotEmpty();
        Assertions.assertThat(rules.stream().filter(rule -> EGRule.class == rule.getClass()).collect(Collectors.toList())).isNotEmpty();
    }
}

CodePudding user response:

You can start a Spring Context using only one (or a few) configuration classes:

@SpringBootTest
@ContextConfiguration(classes = GaRuConfig.class)
public class GaRuConfigTest {
   @Autowired
   private List<GaRu> rules

   @Test
   public void testSomething() {
      // assertion on the rules
   }
}

This will only start an ApplicationContext with that configuration class.

This is especially helpful if you want to test if your configuration in conjunction with the Spring infrastructure (which is not the case in your example). With that test you can verify that there is a bean of type List<GaRu> and it can be Autowired into other classes.

It is cheaper to spin up only a part of your application (in contrast to the whole application), and you can still check if this part is correctly autowired, potentially with a specific @TestConfiguration instead your productive one.

  • Related