Check static method call

I want to check that the method public static void was called .

 @RunWith(PowerMockRunner.class) @PrepareForTest({ConsoleLog.class}) public class AdContentDataUnitTest { @Before public void setUp() throws Exception { PowerMockito.mockStatic(ConsoleLog.class); } @Test public void adContentData_sendTrackingEvent_noUrl() throws Exception { mAdContentData = spy(mAdContentData); // PowerMockito.doNothing().when(ConsoleLog.class); verifyStatic(); mAdContentData.sendTrackingEvent("event1"); //verifyStatic(); } } 

sendTrackingEvent will be called, and ConsoleLog.v(String, String) will be called. In debugging, you can see that the static method is being called, but the following log appears and the test fails:

 Wanted but not invoked com.example.logger.ConsoleLog.v( "AdContentData", "sendTrackingEvent: event event1 does not exist." ); 

I tried adding verifyStatic after the same log, and if I delete the first check, nothing will be verified. If I make fun of the entire ConsoleLog class, an Unfinished stubbing detected here: [...] PowerMockitoCore.doAnswer error occurs Unfinished stubbing detected here: [...] PowerMockitoCore.doAnswer .

Does anyone know how to do this correctly?

+5
source share
1 answer

Does anyone know how to do this correctly?

Yes. Do not do this at all.

Let's say you have a class that calls a static method as follows:

 class Person { private final int id; Person() { id = IdGenerator.gen(); } } 

Extract a static call to a non-static method:

 class Person { private final int id; Person() { id = generateId(); } protected int generateId() { return IdGenerator.gen(); } } 

Now you can write a test by overriding the extracted method:

  final int id = 1; Person person = new Person() { @Override protected int generateId() { return id; } }; // test with person, knowing we control id 

But the ideal solution is to refactor the code under test so as not to use such static calls at all, but to inject dependency.

+3
source

All Articles