Consider two classes A
and B
.
class A { static int a(){} }
class B { void something(){ int value=A.a(); .......}}
Now I have to cover class B
using Junit Test case and hence I create a new class (class TestB
) to cover the class B
.
class TestB { @Test public void testsomething(){...} }
Here my question is if there is any way I can cover the line A.a()
as this is the static method. I know that I can't easy mock it because there is no object involved. So how would I proceed?
I am using JUnit and EasyMock.
As you pointed out there is no way to mock a static method with easymock.
Approach 1: Don't use static methods wherever possible.
Approach 2: Use PowerMock on top of easymock.
Approach 3: Delegate the body of
A.a()
by using a supplier insidea()
. You can than use a "simple" supplier for testcases and the real world supplier for productive use.You will have to use PowerMock along with easymock to mock the static methods.
https://github.com/jayway/powermock/wiki/MockStatic
For your test case mock code will look like this
Here is a working example to mock static method for
KeyStore.getInstance
methodKeyStoreService:
Test class: