Java Mockito:如何忽略可传递依赖项

Java Mockito:如何忽略可传递依赖项,java,junit,mockito,classnotfoundexception,Java,Junit,Mockito,Classnotfoundexception,我正在使用mockito进行单元测试。考虑下面的片段 ThirdPartyClass tpo = mock(ThirdPartyClass.class); doNothing().when(tpo).someMethod(); ThirdPartyClass来自第三方jar,比如说tp.jar。现在tp.jar不是uber-jar。下面是ThirdPartyClass的外观 class ThirdPartyClass { SomeOtherClass memberObject;

我正在使用mockito进行单元测试。考虑下面的片段

ThirdPartyClass tpo = mock(ThirdPartyClass.class);
doNothing().when(tpo).someMethod();
ThirdPartyClass
来自第三方jar,比如说
tp.jar
。现在
tp.jar
不是uber-jar。下面是
ThirdPartyClass
的外观

class ThirdPartyClass
{
    SomeOtherClass memberObject;

    public ThirdPartyClass(){}

    /*Rest of the code*/
}
现在,当我尝试运行单元测试时,我得到了
SomeOtherClass
java.lang.ClassNotFoundException
。请记住,
tp.jar
不是uber jar,因此,
SomeOtherClass
不在我的类路径中是有道理的


但是为什么mockito不能处理这种可传递的依赖关系呢?有没有办法忽略所有可传递依赖项

Mockito通过创建要模拟的类的子类来工作。因此,要模拟的类必须编译。如果要模拟
ThirdPartyClass
,则
SomeOtherClass
必须位于编译时和运行时类路径上,可以通过将包含
SomeOtherClass
的jar添加到具有scope
test

的依赖关系管理中来解决。如果不了解你是如何建立/运行的,就很难提供真正的帮助

您需要确保所有必需的类(JAR)都处于打开状态

  • 编译类路径
  • 运行时类路径
  • 如果您正在使用诸如或之类的构建工具来构建和运行,那么将为您管理类路径,包括可传递的依赖项。如果您是手工编译/运行,则需要确保可传递依赖项位于编译时和运行时类路径上。

    就是这样做的。
    其中一个原因正是您所描述的:测试设置变得太复杂,例如,因为依赖关系

    因此,不要模拟第三方类,而是创建某种适配器,然后模拟该类

    interface ThirdPartyAdapter {
       void someMethod(); // only put method here that you really use
    }
    
    然后嘲笑那件事:

    ThirdPartyAdapter tpo = mock(ThirdPartyAdapter.class);
    doNothing().when(tpo).someMethod();
    
    在生产中,委托给
    第三方类

    class UsefulThing implements ThirdPartyAdapter {
       ThirdPartyClass wrapped;
    
       UsefulThing(ThirdPartyClass wrapped) {
         this.wrapped = wrapped;
       }
    
       @Override
       void someMethod() {
         wrapped.someMethod()
       }
    }
    
    好处:

    • 测试和生产代码对于第三方类的更改更加健壮
    • 您可以使用自己的域术语来表示方法,而不是第三方指定的术语
    • 代码和第三方代码之间的关系变得更加清晰(并且仅在代码中的单个位置可见)

    我强烈建议-或检查快速启动。

    是有意义的,但为此我必须更新pom。此外,我可能不知道
    ThirdPartyClass
    中引用的所有类,通常maven应该处理可传递依赖项的现成解析。显示要模拟的类的maven依赖项。
    asd.pqw.fgh tp 1.0
    这就是我使用maven获取tp.jar所做的一切。然后,您需要检查依赖项的pom文件,可能是它对依赖项使用了某个范围,使它们不可传递。如果是这样,您可以复制有问题的依赖项,并对其进行范围测试。