【发布时间】:2012-03-01 20:52:43
【问题描述】:
我正在尝试为以下方法编写测试类
public class CustomServiceImpl implements CustomService {
@Value("#{myProp['custom.url']}")
private String url;
@Autowire
private DataService dataService;
我在类中的一种方法中使用注入的 url 值。 为了测试这一点,我编写了一个 junit 类
@RunWith(MockitoJUnitRunner.class)
@ContextConfiguration(locations = { "classpath:applicationContext-test.xml" })
public CustomServiceTest{
private CustomService customService;
@Mock
private DataService dataService;
@Before
public void setup() {
customService = new CustomServiceImpl();
Setter.set(customService, "dataService", dataService);
}
...
}
public class Setter {
public static void set(Object obj, String fieldName, Object value) throws Exception {
Field field = obj.getClass().getDeclaredField(fieldName);
field.setAccessible(true);
field.set(obj, value);
}
}
在 applicationContext-test.xml 中,我正在使用
加载属性文件 <util:properties id="myProp" location="myProp.properties"/>
但是在运行测试时,url 值没有加载到 CustomService 中。 我想知道是否有办法完成这项工作。
谢谢
【问题讨论】:
-
如果你在嘲笑
CustomService,那么CustomServiceImpl是如何被使用的呢?这没有意义。 -
我正在使用CustomeServiceImpl。更新了代码。如何模拟需要从属性文件中读取的 url 的值?
-
就目前而言,您没有使用 Spring 设置 customService 值,而是使用以下代码在 setup() 方法中手动设置值:
customService = new CustomServiceImpl(); -
不,我没有使用 spring 来设置测试的 customService 值,但在实际应用程序中,我使用 spring 来设置值。是否可以像我为 dataService 那样模拟 url 的值?
标签: java spring spring-mvc properties mockito