[英]Testing class with ArrayList private member
I have a Java class with following implementation: 我有一个具有以下实现的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);
}
The question is how to test function publicFun()
using Mockito, PowerMock or other testing tool ? 问题是如何使用Mockito,PowerMock或其他测试工具来测试功能
publicFun()
? To run this public function I have to mock private List but how can I do it ? 要运行此公共功能,我必须模拟私有列表,但是我该怎么办呢?
In this example there are several problems caused by unwelcome dependencies: 在此示例中,由于不受欢迎的依赖关系而导致一些问题:
1 new Date()
To solve it I suggest to introduce new interface 1个
new Date()
要解决它,我建议引入新的界面
interface CurrentTimeProvider {
Date getCurrentDate();
}
Implementation is obvious (I skip it for briefness) 实施是显而易见的(为简单起见,我跳过了它)
2 Is new ArrayList()
2
Is new ArrayList()
In result we get something like this: 结果我们得到这样的东西:
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);
}
And test look look this: 并测试一下:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.