Mayank Sinha
Mayank Sinha

Reputation: 41

Mocking static method of same class which needs to be tested in unit test

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?

Upvotes: 1

Views: 2452

Answers (2)

Illyes Istvan
Illyes Istvan

Reputation: 579

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.

Upvotes: 0

GhostCat
GhostCat

Reputation: 140427

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.

Upvotes: 5

Related Questions