从Spring Boot单元测试中排除Spring Cloud Config Server



给定我有以下3个bean:

@Component
public class ServiceConfig {
    // This value is only available from the Spring Cloud Config Server
    @Value("${example.property}")
    private String exampleProperty;
    public String getExampleProperty() {
        return exampleProperty;
    }
}
@Component
public class S1 {
    int i = 1;
}
@Component
public class S2 {
    @Autowired
    S1 s1;
}

我希望能够运行以下测试:

@RunWith(SpringRunner.class)
@SpringBootTest
public class S2Test {
    @Autowired
    S2 s;
    @Test
    public void t2() {
        System.out.println(s.s1.i);
    }
}

我遇到的问题是,由于我想孤立地测试S2类,并且由于它使用@Autowired,因此我必须在测试中具有弹簧上下文,但是当春季上下文启动时,它试图创建所有3个bean,包括带有@Value的豆。由于此值仅来自Spring Cloud Config Server可用,因此无法创建上下文出现错误:org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'serviceConfig': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'example.property' in string value "${example.property}"

我的问题是:如何从春季云配置中读取属性 运行单位测试时在应用程序中处理的服务器,请注意 我的测试我什至不在乎配置,所以我不想明确 必须在我的测试中设置一个值才能开始的上下文?

我建议简单地将" spring.cloud.config.enabled"添加到" src/test/test/resource/application.properties"中的false,然后为" example.property"添加一个测试值..

spring.cloud.config.enabled=false
example.property=testvalue

这很简单,不会影响您的代码库。如果需要,您也可以使用一个模拟的Web环境,以及不包括这些bean的自定义测试应用程序配置。

@SpringBootTest(classes = TestOnlyApplication.class, webEnvironment = SpringBootTest.WebEnvironment.MOCK)

有一些选项。

  1. 您可以创建测试配置文件。然后,您需要创建application-test.ymlapplication-test.properties文件。在那里,您可以为example.property设置相同的值。在那里,如果您想使用test配置文件开始一些测试,则可以添加到测试类@ActiveProfiles("test")注释中。对于这些测试,将开始test

  2. 您可以通过键入@Value("${example.property:SomeDefaultValue}")设置example.property的默认值。如果找不到属性,将插入SomeDefaultValue

我建议第一种方法。您可以用注释设置适当的配置文件,并确保将哪个配置配置服务器发送给您。

最新更新