Abt*_*Pst 0 java junit mockito classnotfoundexception
我正在使用mockito进行单元测试.请考虑以下代码段
ThirdPartyClass tpo = mock(ThirdPartyClass.class);
doNothing().when(tpo).someMethod();
Run Code Online (Sandbox Code Playgroud)
ThirdPartyClass我们是来自第三方的罐子tp.jar.现在tp.jar不是一个超级罐子.这是什么ThirdPartyClass样的
class ThirdPartyClass
{
SomeOtherClass memberObject;
public ThirdPartyClass(){}
/*Rest of the code*/
}
Run Code Online (Sandbox Code Playgroud)
现在,当我尝试运行我的单元测试时,我得到java.lang.ClassNotFoundException了SomeOtherClass.请记住,这tp.jar不是一个超级jar,所以它有意义,SomeOtherClass不在我的类路径中.
但为什么mockito无法处理这种传递依赖?有没有办法忽略所有传递依赖?
"只有你拥有的模拟类型"是这里的方式.
其中一个原因正是您所描述的:测试设置变得过于复杂,例如由于依赖性.
因此,不是ThirdPartyClass模拟,而是创建某种适配器,然后模拟该类.
interface ThirdPartyAdapter {
void someMethod(); // only put method here that you really use
}
Run Code Online (Sandbox Code Playgroud)
然后嘲笑那件事:
ThirdPartyAdapter tpo = mock(ThirdPartyAdapter.class);
doNothing().when(tpo).someMethod();
Run Code Online (Sandbox Code Playgroud)
在制作中,委托给ThirdPartyClass:
class UsefulThing implements ThirdPartyAdapter {
ThirdPartyClass wrapped;
UsefulThing(ThirdPartyClass wrapped) {
this.wrapped = wrapped;
}
@Override
void someMethod() {
wrapped.someMethod()
}
}
Run Code Online (Sandbox Code Playgroud)
优点:
我强烈推荐Freeman&Pryce开发面向对象的软件 - 或者查看mockito docks以便快速入门.
| 归档时间: |
|
| 查看次数: |
431 次 |
| 最近记录: |