java - 在java中模拟调用外部方法

标签 java methods mocking easymock powermock

我有一个关于如何在 java 中模拟某些调用的问题,例如,假设我有这个:

import whatever.package;

Class myClass extends otherClass {

    public void myMethod() {
        ...
        int a = methodCall();
        ...
    }
}

问题是“methodCall()”来自包“whatever.package”,它是从“otherClass”继承而来的。是否可以模拟它以便返回我想要的任何 int?

非常感谢!!

最佳答案

在评论中澄清之后

如果它是继承的,您可以使用我建议的最后一个模式(测试扩展 myClass)并简单地覆盖 methodCall()


在这个答案中,我假设 methodCall() 是您拥有的另一个类的非静态方法。

让我们修改示例代码:

import whatever.package;

Class myClass 
{
    public void myMethod() 
    {
        ...
        anotherClass aClass = new anotherClass();
        int a = aClass.methodCall();
        ...
    }
}

所以,现在我们要模拟 anotherClass 的 methodCall()。

正常的程序是使用接口(interface)并将“接线”推到别处,以避免紧耦合。对依赖注入(inject)和类似概念进行一些研究。

简而言之,使用 new anotherClass() 可以创建紧密耦合。您可以将 anotherClass 对象注入(inject)到 myClass 构造函数中或通过 getter 和 setter 注入(inject)。我假设您需要模拟来编写单元测试。考虑以下代码:

import whatever.package;

Class myClass 
{
    private IanotherClass another;

    public void SetAnotherClass(IAnotherClass aClass)
    {
         another = aClass;
    }

    public void myMethod() 
    {
        ...
         int a = another.methodCall();
        ...
    }
}

测试代码:

   myClass testedClass = new myClass();
   testedClass.SetAnotherClass(new MyAnotherClassMock());
   testedClass.myMethod();

至于注入(inject)依赖项和针对接口(interface)而不是实现进行编程,有很多关于该主题的内容可供阅读 - 只需谷歌一下即可!

如果你不想重新设计你的整个代码并且只需要一个快速(并且有点脏)的修复,你可以考虑将创建 anotherClass 实例移动到单独的方法中,然后简单地让你的测试类继承你的类,覆盖提到方法(这并不总是可能的——完全取决于您的实际代码)

例子:

Class myClass 
{
    public void myMethod() 
    {
        ...
        IanotherClass aClass = GetAnotherClassInstance();
        int a = aClass.methodCall();
        ...
    }

    protected IanotherClass GetAnotherClassInstance()
    {
        return new anotherClass();
    }
}

Class MyTestClass extends myClass
{
   @overwrite
   protected IanotherClass GetAnotherClassInstance()
   {
        return new anotherClassMock();
   }
}

然后只需使用 myTestClass 进行测试!

关于java - 在java中模拟调用外部方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12638713/

相关文章:

java - hashmap中入口类中的hashcode和equals是什么

java - 如何从计时器触发路线

c++ - VSC++,地址错误的虚拟方法,奇怪的错误

java - Java 初级: Method doesn't recognise user input string passed to it

ios - Charles Map Local 不适用于 JSON 数据?

java - 抛出异常后的空白消息对话框

java - 二维数组重写

c++ - 静态方法 C++

unit-testing - 如何使用 Jest 访问单元测试中的全局常量?

javascript - 更新到 Jest 26 后模拟中断