运行单元测试时无法从application.yaml读取值

时间:2018-03-28 12:34:41

标签: java spring spring-boot

我有一个名为Profile的类,它从application.yaml读取第一个Name和Last Name,并使用static 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

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

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应该在classpath中可用,如果你的是Maven项目,那么将你的application.yaml放在src / test / resources文件夹中。