繁体   English   中英

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

[英]Exclude Spring Cloud Config Server from Spring boot unit test

鉴于我有以下3豆:

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

}

我的问题是,因为我想@Autowired测试S2类,因为它使用@Autowired我必须在我的测试中有一个Spring上下文,但是当Spring上下文启动时它会尝试创建包含bean的所有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}" 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 Server中的属性,在我的测试中观察我甚至不关心配置,所以我不想明确地在我的测试中设置一个值只是为了要开始的背景?

我建议只需在“src / test / resources / application.properties”中将“spring.cloud.config.enabled”添加为false,并为“example.property”添加测试值。

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

这很简单,不会影响您的代码库。 如果需要,您还可以使用MOCK 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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM