Java单元测试:替换测试中的私有方法

Jam*_*arr 3 junit osgi unit-testing

在运行JUnit测试时,有没有办法在私有方法中替换逻辑?

一些背景知识:我们有一些私有方法可以与OSGi容器中的bundle进行交互.这在单元测试中不可用,因此方法将失败.

我们已经看过JMockIt但是方法替换功能似乎想要强制你替换类中相互调用的所有方法.

实现将是这样的:

public final doSomething() {  
    firstThing();
    secondThing();
}
private firstThing() {  
    // normal code
}
private secondThing() {  
    // code which is unavailable in a unit test
}
Run Code Online (Sandbox Code Playgroud)

单元测试将指定secondThing()的新实现:

// replace secondThing() in impl with this secondThing()

private secondThing() {  
    // dummy code
}

// run tests
Run Code Online (Sandbox Code Playgroud)

Rog*_*rio 7

你当然可以用JMockit解决这个问题.一种方法是定义"模拟"类,例如:

public class MyTest
{
    @Test
    public void testDoSomething()
    {
        new MockUp<ClassWhichDependsOnOtherBundles>()
        {
            @Mock
            void secondThing()
            {
               // do anything here
            }
        };

        new ClassWhichDependsOnOtherBundles().doSomething();
    }
}
Run Code Online (Sandbox Code Playgroud)

只有被secondThing()模拟的类中的方法才会被JMockit替换.也可以使用JMockit Expectations API,部分模拟.