![](/img/trans.png)
[英]Mock a static method used inside a private method without using powermock
[英]Powermock: How to mock a private method inside a static class
假設我有一個如下的實用程序類:
public final class NumberUtility{
public static int getNumberPlusOne(int num){
return doSomethingFancyInternally(num);
}
private static int doSomethingFancyInternally(int num){
//Fancy code here...
return num;
}
}
假設我不更改類的結構,如何使用Powermock模擬doSomethingFancyInternally()
方法?
為什么不能使用PowerMock模擬getNumberPlusOne
方法? 私有方法不應在測試中可見。
例如,有人更改了私有方法的內部實現(甚至更改了方法名稱),則測試將失敗。
您可以使用java reflection
來訪問class
private
方法。 所以類似的方式,您可以測試此private
方法。
通常為了測試這種情況,可以使用旁路封裝技術。 這是一個示例: https : //code.google.com/p/powermock/wiki/BypassEncapsulation 。 坦白地說,它只是使用java反射API來破壞類的隱私,因此您不必更改類結構即可對其進行測試。
這應該有助於->在類上模擬私有靜態方法
這是我上課的代碼。 我也修改了您的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();
}
}
剪切:公共最終課程NumberUtility {
public static Integer getNumberPlusOne(Integer num){
return doSomethingFancyInternally(num);}
private static Integer doSomethingFancyInternally(Integer num){
//Fancy code here...
return num;}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.