java - 如何抑制构造函数中的私有(private)方法调用?

标签 java unit-testing mocking powermock

我有一个非常非常简单的类,它有一个私有(private)方法。问题是如何抑制这个方法的调用?

这是我的代码:

public class Example { 
    private int value;

    public Example(int value) {
        this.value = value;
        method();
    }

    private void method() {
        throw new RuntimeException();
    }

    public int getValue() {
        return value;
    }
}

以及测试代码(至少尝试):

public void test() throws Exception {

    PowerMockito.doNothing().when(Example.class, "method");
    final int EXPECTED_VALUE = 1;
    Example example = new Example(EXPECTED_VALUE);
    int RETRIEVED_VALUE = example.getValue();

    assertEquals(RETRIEVED_VALUE, EXPECTED_VALUE);
    verifyPrivate(Example.class, times(1)).invoke("method");
}

UPD

对我来说,遵守这两个条款很重要:

  1. PowerMockito.doNothing().when(Example.class, "方法");
  2. PowerMockito.verifyPrivate(Example.class, times(1)).invoke("方法");

最佳答案

因为您无法修改被测试的代码。我认为没有完美的解决方案。您需要部分模拟Example实例。

List list = new LinkedList();
List spy = spy(list);
//You have to use doReturn() for stubbing
doReturn("foo").when(spy).get(0);

但是你不能这样做,因为你必须首先实例化你的对象。

<小时/>

因此,我提出以下由两个测试组成的解决方法。第一个测试从类中删除私有(private)方法,实例化Example并验证Example是否已正确初始化。 第二个测试实例化Example并验证RuntimeException(私有(private)方法副作用)。

import static org.junit.Assert.assertEquals;
import static org.powermock.api.support.membermodification.MemberMatcher.method;
import static org.powermock.api.support.membermodification.MemberModifier.suppress;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
@PrepareForTest(Example.class)
public class ExampleTest {
    @Test
    public void constructor_should_initialize_the_v2alue() throws Exception {
        suppress(method(Example.class, "method"));

        final int EXPECTED_VALUE = 1;
        Example example = PowerMockito.spy(new Example(EXPECTED_VALUE));
        int RETRIEVED_VALUE = example.getValue();

        assertEquals(RETRIEVED_VALUE, EXPECTED_VALUE);
    }

    @Test(expected=RuntimeException.class)
    public void constructor_should_invoke_the_private_method() throws Exception {
        new Example(1);
    }
}

关于java - 如何抑制构造函数中的私有(private)方法调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24560508/

相关文章:

java - java中使用request.getParameter声明字符串时检查字符串是否为空

Java:如何将用户定义的属性的值放入数组中?

Java进程生成器

unit-testing - 犀牛模拟 : "Verify" vs. "Assert"

PHP 模拟最终类

python-3.x - unittest模拟和多重继承: TypeError: metaclass conflict

java - 在多台计算机上运行 Sikuli 脚本

java - 如何在 openGL 应用程序中编写绘制正方形的测试?

Android Studio,Junit4加入classpath后仍无法解析Junit

javascript - 如何使用 Jest 模拟直接导入的函数?