我有一个Java类,具有以下实现:
class Some {
private ArrayList<SomeObject> list = new...
public void addToList(Long t) {
SomeObject so = new SomeObject(new Date, t)
list.add(so)
}
private float fun1(ArrayList<SomeObject> x) {
//some operations on list "list",
//res - result of float calculations based on list "x"
return res
}
public float publicFun() {
//some other operations on private list "list"
return fun1(list);
}
问题是如何使用Mockito,PowerMock或其他测试工具测试函数publicFun()
?要运行这个公共函数,我必须模拟私有List,但我该怎么做呢?
答案 0 :(得分:1)
在此示例中,由不受欢迎的依赖项引起了几个问题:
1 new Date()
为了解决这个问题,我建议引入新的界面
interface CurrentTimeProvider {
Date getCurrentDate();
}
实施是显而易见的(我为了简洁而跳过它)
2 Is new ArrayList()
结果我们得到这样的结果:
class Some {
private CurrentTimeProvider timeProvider;
private ArrayList<SomeObject> list = new ArrayList<SomeObject>();
public void setTimeProvider(CurrentTimeProvider timeProvider) {
this.timeProvider = timeProvider;
}
public void addToList(Long t) {
SomeObject so = new SomeObject(timeProvider.getCurrentDate(), t)
list.add(so)
}
public float publicFun() {
//some other operations on private list "list"
return fun1(list);
}
测试看看这个:
CurrentTimeProvider timeProvider = mock(CurrentTimeProvider.class);
Some some = new Some();
some.setTimeProvider(timeProvider);
when(timeProvider.getCurrentDate).thenReturn(mock(Date.class));
//Invoke you method
some.publicFun();
//Put assert and verify here