当前位置: 首页 > 知识库问答 >
问题:

当父级位于不同的包中时,模拟受保护的父级方法

吉凯捷
2023-03-14
    null
package parent;

public class Parent {

    // Want to mock this protected parent method from different package
    protected String foo() {

        String someValue = null;

        // Logic setting someValue

        return someValue;
    }
}

Child.java

package child;

import parent.Parent;

public class Child extends Parent {

    String fooString = null;

    public String boo() {

        this.fooString = this.foo();

        String booString = null;

        // Logic setting booString

        return booString;
    }
}

ChildTest.java

package child;

import static org.mockito.Mockito.spy;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

import parent.Parent;

@RunWith(PowerMockRunner.class)
@PrepareForTest({ Parent.class, Child.class })
public class ChildTest {

    // Class Under Test
    Child cut;

    @Before
    public void setUp() throws Exception {

        // Partial mock to mock methods in parent class
        cut = spy(new Child());

    }

    @Test
    public void testBoo() {

        // TODO: Need to mock cut.foo() but can't figure out how.

        // Following gives me this error: The method foo() from the type Parent is not visible
       Mockito.when(((Parent)cut).foo()).thenReturn("mockValue");

        // Test
        cut.boo();

        // Validations
        Assert.assertEquals(cut.fooString, "mockValue");

    }
}

共有1个答案

伏业
2023-03-14

只需创建一个用于测试的新类,扩展您要测试的类,并在那里重写您的方法

看起来是这样的:

public class ChildForTest extends Child{
     @Override
     protected String foo() {
         //mock logic here
    }
}

编辑:如果你想避免新的类定义,你可以使用匿名类

@Before
public void setUp() throws Exception {

    // Partial mock to mock methods in parent class
    cut = new Child(){
        @Override
        protected String foo(){
            //mock logic here
            return "";
        }
    };
}
 类似资料:
  • 我尝试模拟父类的受保护方法。因此,我使用&。我的家长班。

  • 问题内容: 我遇到了一个奇怪的问题,我无法弄清楚在尝试插入程序时弹出的问题。另一个问题是我无法创建一个简单的测试用例,因为每次尝试都可以。我一定缺少一些并发症。但我会尽力清楚地描述这种情况,以防任何人熟悉。 我有一个称为Seed的基类,它是主应用程序的一部分,并由系统类加载器加载。我有一个包含Road类的插件,该类是Seed的子类。它是在运行时从单独的jar文件加载的。Road类引用字段Seed.

  • 我在React中有一个名为“app”的父组件,它用HighCharts实现呈现一个“卡路里”子组件。 以下是我的完整代码: 谁能帮我做错了什么?

  • 问题内容: 我不知道是否存在问题,但是我想知道为什么在父/子元素上不能使用。 这是一个例子: CSS和HTML: 问题答案: 因为固定位置元素是相对于视口而不是其他元素固定的。因此,由于视口没有切断,因此溢流变得无关紧要。 具有position:absolute的元素的位置和尺寸相对于其包含块,而具有position:fixed的元素的位置和尺寸始终相对于初始包含块。通常是视口:浏览器窗口或纸张的

  • 问题是要确定子数据的总和是否等于父数据。如果是,返回真,否则返回假。 下面是我的代码,在提交时出现错误。我知道这是一个简单的问题,但在编写了条件之后,我很难通过遍历所有左右节点来递归检查二叉树中每个节点的和条件。 请指导我,因为我哪里做错了。

  • 我在另一个div中有两个div,我想使用CSS将一个子div放置在父div的右上方,另一个子div放置在父div的底部。例如,我想对两个子div使用绝对定位,但是相对于父div而不是页面定位它们。我怎么能这么做? HTML示例: