blo*_*824 6 java spring properties mockito
我正在尝试在我的控制器中为以下方法编写单元测试.
@Autowired
private ApplicationContext context;
private String getProperty() {
try {
Properties props = context.getBean("myProperties", Properties.class);
String val = props.getProperty("myProperty");
......
Run Code Online (Sandbox Code Playgroud)
Bean在我的applicationContext中声明如下:
<util:properties id="myProperties" scope="prototype" location="file:${catalina.base}/webapps/myProperties.properties"/>
Run Code Online (Sandbox Code Playgroud)
我如何模拟这个以便我可以测试val变量的不同值?
我想过创建一个测试属性文件并像这样嘲笑它:
context = Mockito.mock(ApplicationContext.class);
Mocikto.when(context.getBean("myProperties", Properties.class)).thenReturn(some test file)
Run Code Online (Sandbox Code Playgroud)
但是我必须将测试文件声明为某个bean.
我想知道是否有更简单的方法来做到这一点?
谢谢
如果你使用的是spring-3,你可以:
<context:property-placeholder location="myprops.properties" />
Run Code Online (Sandbox Code Playgroud)
在你的代码中:
@Value("${myProperty}")
private String myProp;
public String getMyProp() {
return myProp;
}
Run Code Online (Sandbox Code Playgroud)
这使得myprops.properties可以通过$ {...}表达式用于变量替换,而@Value注释允许值注入属性.然后在单元测试中,您可以简单地设置myProp的不同值.
| 归档时间: |
|
| 查看次数: |
17167 次 |
| 最近记录: |