5
class StaticClass {
  public static String a(){ return "a"; }
  public static String ab(){ return a()+"b"; }
}

I want to mock StaticClass::a so that it returns "x" and the call to StaticClass.ab() results in "xb"...

I find it very hard in PowerMock and TestNG...


the exact code I am testing righ now:

class StaticClass {
    public static String A() {
        System.out.println("Called A");
        throw new IllegalStateException("SHOULD BE MOCKED AWAY!");
    }

    public static String B() {
        System.out.println("Called B");
        return A() + "B";
    }
}

@PrepareForTest({StaticClass.class})
public class StaticClassTest extends PowerMockTestCase {

    @Test
    public void testAB() throws Exception {
        PowerMockito.spy(StaticClass.class);
        BDDMockito.given(StaticClass.A()).willReturn("A");
        assertEquals("AB", StaticClass.B()); // IllegalStateEx is still thrown :-/
    }

}

I have Maven dependencies on:

<artifactId>powermock-module-testng</artifactId>
and
<artifactId>powermock-api-mockito</artifactId>
Parobay
  • 2,549
  • 3
  • 24
  • 36

2 Answers2

10

Why not try something like :

PowerMockito.mockStatic(StaticClass.class);
Mockito.when(StaticClass.a()).thenReturn("x");
Mockito.when(StaticClass.ab()).thenCallRealMethod();
user3575425
  • 478
  • 3
  • 11
  • 1
    He's using TestNG and not Mockito. – DLight Nov 28 '16 at 15:30
  • 2
    what if, the method returns nothing (void), is this still possible? how about my static class has 20 static methods and I only want to mock one of the methods? – Marquez May 31 '18 at 21:52
  • @Marquez yes, it's still possible for void method. In case the ab() is a void method which returns nothing, it could be like this: PowerMockito.when(StaticClass.class, "ab").thenCallRealMethod(); – garykwwong Apr 02 '20 at 11:22
2

I think this can be accomplished with a Partial Mock.

PowerMock.mockStaticPartial(Mocked.class, "methodToBeMocked");

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

abourg28
  • 575
  • 2
  • 5
  • 10
  • This sounds ok. To be honest though, I very much **dislike specifying a method ... by string name**... This would be a horror to maintain w/o a good IDE. Any way to mock by writing actual Java code (in other words: mock just like an ordinary method)? – Parobay Dec 06 '13 at 07:33
  • That is a good point. I think you can also accomplish this with a spy. See http://stackoverflow.com/questions/4860475/powermock-mocking-of-static-methods-return-original-values-in-some-particula#answer-5063228 – abourg28 Dec 06 '13 at 15:38