Java 测试私有方法时未加载配置值
我有一门课:Java 测试私有方法时未加载配置值,java,spring,unit-testing,Java,Spring,Unit Testing,我有一门课: @Service public class MyService{ @Value("${some.value}") private String someValue; private String someMethod(String inputString){ return inputString == null || inputString.isEmpty() ? someValue : inp
@Service
public class MyService{
@Value("${some.value}")
private String someValue;
private String someMethod(String inputString){
return inputString == null || inputString.isEmpty() ? someValue : inputString;
}
}
在属性文件中,some.value定义如下:
some.value=SomeValue
然后,我尝试使用ReflectionTestUtils测试someMethod:
public class MyTest{
@Value("${some.value}")
private String someValue;
@Autowired
private MyService myService;
@Test
public void testSomeMethod() {
Assert.assertEquals(someValue, ReflectionTestUtils.invokeMethod(myService, "someMethod", ""));
}
}
我得到以下错误:
java.lang.AssertionError:Expected:SomeValue实际值:null
调试时,我看到在我正在测试的服务中,配置值为null
(对我来说:)更奇怪的是,如果我将某个方法从私有更改为公共,一切都会正常工作。在类中添加此注释:
@RunWith(SpringJUnit4ClassRunner.class)
@PropertySource("classpath:name-file.properties ")
在测试添加文件的包资源中:
src/test/resources/name-file.properties
让我猜这不是您正在测试的实际代码,而是一个简化版本,在您的实际应用程序中,您有需要/需要AOP(如事务、安全性等)的代码。这是一个简化版本。因为在这个项目中还有很多其他的东西,我认为它们并不相关,你需要知道什么具体的东西吗?如果你使用AOP或不使用AOP,你需要知道(尽管我怀疑我已经知道答案)。我怀疑你在这里发布的示例(没有AOP)会起作用,但是一旦你在混合中添加AOP,它(似乎)就不起作用了。它不起作用,我的属性文件已经在src/test/resources下了。问题是,它不仅在测试私有方法时起作用;