【发布时间】:2015-06-11 21:45:53
【问题描述】:
我有一个我想测试的方法 (method1),它基于提供的参数创建一个对象并调用另一个方法 (method2)。所以我在嘲笑method2,它接受一个对象(sampleObj)。
public void method1(booleanParam) {
if(booleanParam){
List<SampleObj> fooList = new ArrayList<SampleObj>;
fooList.add(new SampleObj("another param"));
anotherService.method2(fooList);
}
//some other smart logic here
}
这是我用相同的混淆名称进行的测试(抱歉,如果我错过了任何错字):
public void testMethod1() {
AnotherService mockedAnotherService = PowerMockito.mock(AnotherService.class);
ServicesFactory.getInstance().setMock(AnotherService.class, mockedAnotherService);
List<SampleObj> fooList = new ArrayList<SampleObj>;
fooList.add(new SampleObj("another param"));
// assert and verify
service.method1(true);
Mockito.verify(mockedAnotherService, times(1)).method2(fooList);
}
问题是,当我尝试模拟 anotherService 时,我需要将一个对象传递给 method2,所以我必须创建一个新对象。但由于它是一个新对象,它不是同一个对象,它将从 method1 内部传递,因此测试失败并出现异常:
Argument(s) are different! Wanted:
anotherService.method2(
[com.smart.company.SampleObj@19c59e46]
);
-> at <test filename and line # here>
Actual invocation has different arguments:
anotherService.method2(
[com.smart.company.SampleObj@7d1a12e1]
);
-> at <service filename and line # here>
有什么想法可以实现吗?
【问题讨论】:
标签: unit-testing junit mockito powermock