Powermock私有方法

简单笔记下,如有以下待测方法callSumXX,其调用了private方法sumXX

可以直接mock掉callSumXX,传送门:Mockito在Maven junit测试中的应用

如果方法中还有其他待测逻辑等原因不能直接mock掉的话,这里就需要去mock被调用的private方法。

public class Calculator {
    private int sumXX(int a, int b) {
		return a + b;
	}
    
    public int callSumXX(int a, int b){
    	return sumXX(a, b);
    }
}

1.powermock private method的方法

spy被测类:
Calculator powerMock = PowerMockito.spy(new Calculator());

构造返回:
PowerMockito.when(powerMock, "sumXX", 1, 2).thenReturn(2);

断言:
assertEquals(2, powerMock.callSumXX(1, 2));

完整代码如下:
@RunWith(PowerMockRunner.class)
@PrepareForTest({Calculator.class})
public class CalculatorTest {
	
	private Calculator test;

	@BeforeClass
	public static void setUpBeforeClass() throws Exception {
	}

	@AfterClass
	public static void tearDownAfterClass() throws Exception {
	}

	@Before
	public void setUp() throws Exception {
		test = new Calculator();
	}

	@After
	public void tearDown() throws Exception {
	}

	@Test
	public void testSumXX() throws Exception {
		Calculator powerMock = PowerMockito.spy(new Calculator());
		PowerMockito.when(powerMock, "sumXX", 1, 2).thenReturn(2);
		assertEquals(2, powerMock.callSumXX(1, 2));
	}
}

测试发现pass了


说明private方法sumXX被成功mock(1+2=2)

2.需要注意的几个问题

a.需要加入@RunWith和@PrepareForTest,见上面的完整代码

b.PowerMockito需要配合Mockito使用,这里版本有对应关系要求:
Mockito                     | PowerMock
------------------------------------------------------------------------------
2.0.0-beta - 2.0.42-beta    |   1.6.5+
------------------------------------------------------------------------------
1.10.19                     |   1.6.4
1.10.8 - 1.10.x             |   1.6.2+
1.9.5-rc1 - 1.9.5           |   1.5.0 - 1.5.6
1.9.0-rc1 & 1.9.0           |   1.4.10 - 1.4.12
1.8.5                       |   1.3.9 - 1.4.9
1.8.4                       |   1.3.7 & 1.3.8
1.8.3                       |   1.3.6
1.8.1 & 1.8.2               |   1.3.5
1.8                         |   1.3
1.7                         |   1.2.5
否则可能出现错误如:
java.lang.NoSuchMethodError:org.mockito.internal.creation.MockSettingsImpl.setMockName(Lorg/mockito/mock/MockName;)Lorg/mockito/internal/creation/settings/CreationSettings

c.maven中powermock的引入:
  
    UTF-8
    1.6.4
  
	
      org.powermock
      powermock-module-junit4
      ${powermock.version}
      test
   
   
      org.powermock
      powermock-api-mockito
      ${powermock.version}
      test
   


你可能感兴趣的:(Powermock私有方法)