【发布时间】:2011-09-17 08:02:28
【问题描述】:
我正在尝试在我的控制器中为以下方法编写单元测试。
@Autowired
private ApplicationContext context;
private String getProperty() {
try {
Properties props = context.getBean("myProperties", Properties.class);
String val = props.getProperty("myProperty");
......
Bean 在我的 applicationContext 中是这样声明的:
<util:properties id="myProperties" scope="prototype" location="file:${catalina.base}/webapps/myProperties.properties"/>
我怎样才能模拟这个,以便我可以测试 val 变量的不同值?
我想过创建一个测试属性文件并像这样模拟它:
context = Mockito.mock(ApplicationContext.class);
Mocikto.when(context.getBean("myProperties", Properties.class)).thenReturn(some test file)
但是我必须在某处将测试文件声明为 bean。
我想知道是否有更简单的方法可以做到这一点?
谢谢
【问题讨论】:
-
你在使用 Spring MVC 吗?您可以简单地在 Controller 上定义一个字段并在控制器的 bean 定义中为其设置一个值,而不是为您的控制器提供对 ApplicationContext 的引用并从中提取值。然后测试就不是问题了,因为您可以在测试中随意初始化控制器 - 根本不需要模拟应用程序上下文。
标签: java spring properties mockito