Spring 启动测试无论如何都找不到属性
Spring Boot Test Cannot find Properties No Matter What
我有一个简单的豆子
public class MyBean {
@Value("${propItem}")
private boolean propItem;
public String someMethod() {
if (propItem) {
return "XX";
} else {
return "XY";
}
}
}
我在 src/test/resources
中有一个名为 application-test.yml
的属性文件,其中有一个 属性
propItem: true
如果我 运行 下面的测试 - 我希望它通过,但它失败了,因为 propItem
总是 false
@SpringBootTest
public class MyBeanTest {
public void testFunc() {
assertTrue(new MyBean().someMethod().equals("XX"); // Fails because it's "XY"
}
}
为什么这是个问题?我以为 Spring 会自动完成所有这些操作,但似乎不会
您正在手动实例化 mybean,这样 属性 将不会被注入。您需要从上下文中获取 bean。
您需要:
- 通过添加构造型注释将
MyBean
定义为 bean:@Component
、@Configuration
或 @Service
- 在您的测试中定义一个活动配置文件 class:
@ActiveProfile("test")
您的 class 应如下所示:
@Component
public class MyBean {
@Value("${propItem}")
private boolean propItem;
public String someMethod() {
if (propItem) {
return "XX";
} else {
return "XY";
}
}
}
你的测试class:
@SpringBootTest
@ActiveProfile("test")
public class MyBeanTest {
@Autowired
private MyBean myBean;
@Test
public void testFunc() {
assertTrue(myBean.someMethod().equals("XX")); // Fails because it's "XY"
}
}
我有一个简单的豆子
public class MyBean {
@Value("${propItem}")
private boolean propItem;
public String someMethod() {
if (propItem) {
return "XX";
} else {
return "XY";
}
}
}
我在 src/test/resources
中有一个名为 application-test.yml
的属性文件,其中有一个 属性
propItem: true
如果我 运行 下面的测试 - 我希望它通过,但它失败了,因为 propItem
总是 false
@SpringBootTest
public class MyBeanTest {
public void testFunc() {
assertTrue(new MyBean().someMethod().equals("XX"); // Fails because it's "XY"
}
}
为什么这是个问题?我以为 Spring 会自动完成所有这些操作,但似乎不会
您正在手动实例化 mybean,这样 属性 将不会被注入。您需要从上下文中获取 bean。
您需要:
- 通过添加构造型注释将
MyBean
定义为 bean:@Component
、@Configuration
或@Service
- 在您的测试中定义一个活动配置文件 class:
@ActiveProfile("test")
您的 class 应如下所示:
@Component
public class MyBean {
@Value("${propItem}")
private boolean propItem;
public String someMethod() {
if (propItem) {
return "XX";
} else {
return "XY";
}
}
}
你的测试class:
@SpringBootTest
@ActiveProfile("test")
public class MyBeanTest {
@Autowired
private MyBean myBean;
@Test
public void testFunc() {
assertTrue(myBean.someMethod().equals("XX")); // Fails because it's "XY"
}
}