如何在不启动整个上下文的情况下在 Spring 中测试 @Configuration class?

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

如何在不启动整个 Spring 上下文的情况下测试我的配置 class 或者我应该这样做吗?

@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);
    }
}

有没有办法测试这个class?

使用 AssertJ 您可以执行以下操作:

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();
        
        Assertions.assertThat(rules).hasSize(4);
        Assertions.assertThat(SSRule.class == rules.get(0).getClass()).isTrue();
        Assertions.assertThat(CSRule.class == rules.get(1).getClass()).isTrue();
        Assertions.assertThat(DGRule.class == rules.get(2).getClass()).isTrue();
        Assertions.assertThat(EGRule.class == rules.get(3).getClass()).isTrue();
    }
}

您可以仅使用一个(或几个)配置启动一个 Spring 上下文 classes:

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

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

   @TestConfiguration
   static class MyTestConfig {
     //... overwriting some beans you want to have changed for your test
   }
}

这只会启动具有该配置的 ApplicationContext class。

如果您想测试您的配置是否与 Spring 基础设施(在您的示例中不是这种情况)一起测试,这将特别有用。通过该测试,您可以验证是否存在类型为 List<GaRu> 的 bean,并且它可以自动连接到其他 classes.

仅启动应用程序的一部分(与整个应用程序相比)成本更低,并且您仍然可以检查这部分是否正确自动装配,可能使用特定的 @TestConfiguration 覆盖一些 beans您的生产配置。