0

假设我有一个这样的实用程序类:

public final class NumberUtility{

public static int getNumberPlusOne(int num){

   return doSomethingFancyInternally(num);

}

private static int doSomethingFancyInternally(int num){

      //Fancy code here...

  return num;

}

}

假设我不改变类的结构,如何doSomethingFancyInternally()使用 Powermock 模拟方法?

4

4 回答 4

0

这应该会有所帮助-> 在类上模拟私有静态方法

http://avricot.com/blog/index.php?post/2011/01/25/powermock-%3A-mocking-a-private-static-method-on-a-class

这是我的课程代码。我也修改了你的 CUT。

测试类:

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

@RunWith(PowerMockRunner.class)    
@PrepareForTest({ NumberUtility.class })
public class NumberUtilityTest {

// Class Under Test
NumberUtility cut;

@Before
public void setUp() {

    // Create a new instance of the service under test (SUT).
    cut = new NumberUtility();

    // Common Setup
    // TODO
}

/**
 * Partial mocking of a private method.
 * 
 * @throws Exception
 * 
 */
@Test
public void testGetNumberPlusOne1() throws Exception {

    /* Initialization */
    PowerMock.mockStaticPartial(NumberUtility.class,
            "doSomethingFancyInternally");
    NumberUtility partialMockCUT = PowerMock.createPartialMock(
            NumberUtility.class, "doSomethingFancyInternally");
    Integer doSomethingFancyInternallyOutput = 1;
    Integer input = 0;

    /* Mock Setup */
    PowerMock
            .expectPrivate(partialMockCUT, "doSomethingFancyInternally",
                    EasyMock.isA(Integer.class))
            .andReturn(doSomethingFancyInternallyOutput).anyTimes();

    /* Activate the Mocks */
    PowerMock.replayAll();

    /* Test Method */
    Integer result = NumberUtility.getNumberPlusOne(input);

    /* Asserts */
    Assert.assertEquals(doSomethingFancyInternallyOutput, result);
    PowerMock.verifyAll();

}

}

CUT:公共最终类 NumberUtility{

public static Integer getNumberPlusOne(Integer num){

return doSomethingFancyInternally(num);} 

private static Integer doSomethingFancyInternally(Integer num){

  //Fancy code here...

return num;} 

}
于 2013-11-08T13:26:59.767 回答
0

通常为了测试这种情况,可以使用 Bypass 封装技术。这是一个例子:https ://code.google.com/p/powermock/wiki/BypassEncapsulation 。坦率地说,它只是通过使用 java 反射 API 来破解类隐私,所以你不必被迫改变你的类结构来测试它。

于 2013-11-08T09:04:18.647 回答
0

为什么不能getNumberPlusOne用 PowerMock 模拟方法?私有方法不应该在测试中可见。

例如,有人更改私有方法的内部实现(甚至更改方法名称),那么您的测试将失败。

于 2013-11-08T08:54:44.990 回答
0

您可以java reflection使用private. class所以类似的方式你可以测试这个private方法。

于 2013-11-08T08:55:02.480 回答