1

I have a class that have multiple static method. 1 static method calls 1 other private method which eventually calls second public static method. I want to mock the second static method. Is that possible. e.g.

public static A(){
    b();
} 
private static b(){
    c();
}
public static c(){
}

I want to mock c() but want to keep functionality of a() and b() as it is. Is this possible? If so, how?

  • And just for the record: dont forget about accepting an helpful answer at some point, newbies too often ... forget about that part ;-) – GhostCat Oct 31 '18 at 12:47

2 Answers2

5

This existing SO question tells you how to do that using PowerMockito, and static mocking, and the spy concept of Mockito.

But what is missing from that input: albeit these technical solutions work, you should consider to not go down that path.

Instead: you created a hard to test design. Now you are looking towards (black) mocking magic to enable testing. The real answer is: step back, and evaluate your design. Try to rework it so it becomes easy to test.

Anything else is a waste of time and energy in the long run. Because hard-to-test designs are also hard-to-test in "real" scenarios, and they are most often inflexible and hard to maintain/enhance over time.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
  • 3
    I appreciate it when answers redirect to the correct clean path instead of just pointing to a solution that can solve the problem but really shouldn't be used because it encourages poor design . – Nkosi Oct 31 '18 at 12:24
  • @Nkosi You are welcome. Just the other week we ran into an old PowerMock unit test that another team wrote some years back. We didn't change *anything* related to it, but all of a sudden, that test was failing for us, preventing our builds to pass. One really stays away from PowerMock(ito) unless you absolutely have no other alternative ... – GhostCat Oct 31 '18 at 12:47
0

As @GhostCat mentioned: the need for mocking static methods is smell of bad design, so you should first of all consider refactoring your code so that you won't need static mocking.

Mockito does not support mocking of static methods. More details here

You can use PowerMockito instead.

For example:

PowerMockito.stub(PowerMockito.method(YourStaticClass.class, "c")).toReturn("someValue"); 

BTW: seems your methods do not have a return type.

Illyes Istvan
  • 569
  • 7
  • 19