Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This should help-> Mocking a private static method on a class</p> <p><a href="http://avricot.com/blog/index.php?post/2011/01/25/powermock-%3A-mocking-a-private-static-method-on-a-class" rel="nofollow">http://avricot.com/blog/index.php?post/2011/01/25/powermock-%3A-mocking-a-private-static-method-on-a-class</a></p> <p>Here's my code for your class. I modified your CUT too.</p> <p>TEST CLASS:</p> <pre><code>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(); } } </code></pre> <p>CUT: public final class NumberUtility{</p> <pre><code>public static Integer getNumberPlusOne(Integer num){ return doSomethingFancyInternally(num);} private static Integer doSomethingFancyInternally(Integer num){ //Fancy code here... return num;} } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload