java - JMockit - 部分模拟和模拟父级

标签 java unit-testing mocking jmockit partial-mocks

我想测试(使用 JMockit)一个如下所示的类:

class MyClass extends ComplexParentClass {

    public void testedMethod() {
        ...
    }

    private int complexPrivateMethod() {
        ...
    }

}

我无法更改类(class)。问题在于 ComplexParentClass 有一个复杂的构造函数,这使得测试变得困难。所以我想 mock 父类。我还想模拟复杂的私有(private)方法。但这样的事情可能吗?

我尝试了以下方法:

class MyClassTest {

    @Tested
    MyClass myClass;

    // mock the parent
    @Mocked
    ComplexParentClass complexParentClass;

    @Test
    public void test() {
        new Expectations(myClass) {{
            // partially mock the private method
            Deencapsulation.invoke(myClass, "complexPrivateMethod"); result = 0;
        }};

        myClass.testedMethod();
    }

}

这会导致“已经 mock ”异常。

有人知道如何解决这个问题吗?

最佳答案

您尝试过使用 MockUp 吗?像这样的东西只会模拟 complexPrivateMethod :

@Test public void test() {
  new MockUp<ComplexParentClass> () {
    @Mock private int complexPrivateMethod() { return 0; }
  };

  //do something with MyClass
}

关于java - JMockit - 部分模拟和模拟父级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32253101/

相关文章:

java - 空指针异常 : Attempt to invoke virtual method 'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a null object reference

java - 如何测试/模拟这个静态工厂(用于图形构建)?

unit-testing - WatiN 测试记录器 : How to get the compiled code in C# from the steps the recorder records

c# - 从命令行运行单元测试

java - 如何使用 MockMvc 测试 REST Controller

properties - 是否可以在 Simpletest 中设置 Mock 对象的属性

java - 如何为 Sonar 配置另一个与默认版本不同的java版本?

java - 在 Java 中启动连接的 telnet cmd 窗口

java - 在耶拿使用紧凑 URI

Python:如何模拟 SQLAlchemy 事件处理程序(使用 mock.unittest)