【问题标题】:Unable to read values from application.yaml when running unit tests运行单元测试时无法从 application.yaml 读取值
【发布时间】:2018-03-28 12:34:41
【问题描述】:

我有一个名为 Profile 的类,它从 application.yaml 读取名字和姓氏,并使用静态 print() 方法打印全名。代码如下:

@Component
public final class Profile {

private static final String NAME = "config.firstName";
private static final String LAST_NAME = "config.lastName";

private static String name;
private static String lastName;


    public Profile(
       @Value("${" + NAME + "}") final String name,
       @Value("${" + LAST_NAME + "}") final String lastName) {

       Profile.name = notNull(name);
       Profile.lastName = notNull(lastName);
    }

    public static String print() {
       return name + " " + lastName;

    }
}

我写了一个单元测试来测试这个,这里是代码:

import static org.junit.Assert.assertEquals;

import org.junit.Test;

public class PrintTest {

   @Test
   public void testPrint() {
      String fullName = Hello.print();
      assertEquals("John Smith", fullName);
   }
} 

当我运行单元测试时,我得到 "null null" 而不是 John Smith

有人可以帮忙吗?

【问题讨论】:

  • 为什么要... 你有一个 Spring 范围之外的类,你希望它自动被注入值。您至少必须使用 spring 配置实例并使用 Spring 托管实例。

标签: java spring spring-boot


【解决方案1】:

Profile 是一个 Spring 组件,ApplicationContext 为您初始化 bean。你的测试类应该是这样的,

import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestPropertySource;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations= "classpath:applicationContext.xml")
@TestPropertySource(locations = "classpath:application.yaml")
public class PrintTest {
@Autowired
private Profile profile;

   @Test
   public void testPrint() {
      String fullName = profile.print();
      assertEquals("John Smith", fullName);
   }

}

application.yaml 应该在类路径中可用,如果您的项目是 Maven 项目,则将您的 application.yaml 放在 src/test/resources 文件夹中。

【讨论】:

    猜你喜欢
    • 2015-08-04
    • 1970-01-01
    • 2018-08-08
    • 1970-01-01
    • 1970-01-01
    • 2012-03-28
    • 2016-03-23
    • 2013-10-11
    • 1970-01-01
    相关资源
    最近更新 更多