这是一个Spring bean的片段:
@Component public class Bean { @Value("${bean.timeout:60}") private Integer timeout; // ... }
现在我想用JUnit测试来测试这个bean.因此我使用SpringJUnit4ClassRunner和ContextConfiguration注释.
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration public class BeanTest { @Autowired private Bean bean; // tests ... @Configuration public static class SpringConfiguration { @Bean public Bean bean() { return new Bean(); } } }
不幸的是,SpringJUnit4ClassRunner无法解析@Value
表达式,即使提供了默认值(抛出NumberFormatException).似乎跑步者甚至无法解析表达式.
我的测试中缺少什么?
你的测试@Configuration
类缺少一个实例,PropertyPlaceholderConfigurer
这就是为什么Spring不知道如何解决这些表达式的原因; 在您的SpringConfiguration
类中添加如下所示的bean
@org.springframework.context.annotation.Bean public static PropertyPlaceholderConfigurer propertyPlaceholderConfigurer() { PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer(); ppc.setIgnoreResourceNotFound(true); return ppc; }
并将其移动到一个单独的类并使用
@ContextConfiguration(classes=SpringConfiguration.class)
在运行测试时更具体.