PowerMock: a mocking static method that affects only one test

My situation:

I want to add a new test. And I need to make fun of one static X method of the Service class. Unfortunately, existing tests somehow use this static method.

And when I mock the X method using PowerMock, then another test failed. Moreover, I should not touch on other tests.

Is it possible to mock static methods for only one test? (using PowerMock).

Thanks in advance.

+4
source share
2 answers

Of course it is possible! The only time you can run into problems is when you try to test multiple threads at the same time ... I will give an example of how to do this. Enjoy it.

import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.easymock.PowerMock; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import static org.easymock.EasyMock.*; import static org.junit.Assert.*; @RunWith(PowerMockRunner.class) @PrepareForTest(IdGenerator.class) public class TestClass { @Test public void yourTest() { ServiceRegistrator serTestObj = new ServiceRegistrator(); PowerMock.mockStatic(IdGenerator.class); expect(IdGenerator.generateNewId()).andReturn(42L); PowerMock.replay(IdGenerator.class); long actualId = IdGenerator.generateNewId(); PowerMock.verify(IdGenerator.class); assertEquals(42L,actualId); } @Test public void unaffectedTest() { long actualId = IdGenerator.generateNewId(); PowerMock.verify(IdGenerator.class); assertEquals(3L,actualId); } } 

Testclass

 public class IdGenerator { public static long generateNewId() { return 3L; } } 
+1
source

The easiest way to solve your problem is to create a new test class and post your tests there.

You can also wrap this static class with a regular class, hidden behind the interface in your code, and stub this interface in your tests.

The last thing you can try is to mute every method of your static class in the @SetUp method using:

.

Mockito.when (StaticClass.method (pairs)) thenCallRealMethod ();

and get the specific method in your test using: Mockito.when (Static.methodYouAreInterested (pairs)) thenReturn (value) ;.

0
source

Source: https://habr.com/ru/post/1487370/


All Articles