如何在Spring Boot中将属性注入到测试类中?

时间:2019-10-09 17:38:55

标签: java spring-boot

如何在Spring Boot中将我的application-test.properties中的属性加载到我的测试类中?我在做错事,但无法弄清楚?

我能够从application.properties中获取下面给出的我的Configuration类的属性

package org.vinodh.testing;

import java.util.Map;

import org.junit.Test;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestPropertySource;

import lombok.Data;

@RunWith(SpringRunner.class)
@ContextConfiguration
@ConfigurationProperties(prefix = "caching")
@TestPropertySource("/application-test.properties")
@Data
public class CachingConfigTest {

    @Value("${caching.name}")
    private String name;

    @Data
    public static class CacheSpec {
        private int minutesToExpire;
        private int maximumSize;
    }

    private Map<String, CacheSpec> specs;

    @Test
    public void test() {
        System.out.println(name);
        System.out.println(specs);
    }

}

但是当我尝试在测试类中执行相同操作时,会得到null,请参见以下代码。如何获取测试类以打印属性文件中的值?

caching.specs.test.minutesToExpire=10
caching.specs.test.maximumSize=10
caching.name=Vinodh

application.properties

caching.specs.test.minutesToExpire=10
caching.specs.test.maximumSize=10
caching.name=Vinodh

application-test.properties

import "fmt"

// A simple interface with one function
type myinter interface {
    hello()
}

// Implement myinter
type mystruct struct {}

func (mystruct) hello() {
    fmt.Println("I am T!")
}

// Some function that calls the hello function as defined by myinter
func callHello(i *myinter) {   
    i.hello()  // <- cannot resolve reference 'hello'
}

func main() {
    newMystruct := &mystruct{}
    callHello(newMystruct)
}

2 个答案:

答案 0 :(得分:1)

实际上,您不需要在测试类中创建CacheSpec,这也不建议这样做,您可以使用源代码包中的原始版本。但是只需将getter添加到specs

中的私有地图CachingConfig
@RunWith(SpringRunner.class)
@SpringBootTest
@ActiveProfiles("test")
@Profile("test")
public class CachingConfigTest {

    @Autowired
    private CachingConfig cachingConfig;

    @Test
    public void test() {
        System.out.println(cachingConfig.getSpecs());
     }

 }

而且您也不需要@TestPropertySource,您可以使用@Profile加载测试配置文件,并使用@ActiveProfiletest用作该测试类的活动配置文件< / p>

答案 1 :(得分:0)

尝试一下     spring.config.additional-location = classpath:/application-test.properties