Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerMock: Mocking static method that affect one test only

My situation:

I would like to add a new test. And I need to mock one static method X of Service class. Unfortunately existing tests are using this static method in some way.

And when I mock X method using PowerMock then other test failed. What is more I shouldn't touch other tests.

Is there any opportunity to mock static methods for one test only? ( using PowerMock).

Thanks in advance.

like image 862
Areo Avatar asked Oct 22 '22 07:10

Areo


1 Answers

Sure, it is possible! The only time when you could run into problems is if you are trying to test multiple threads at the same time... I put an example of how to do it below. Enjoy.

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;
      }
}
like image 126
HardcoreBro Avatar answered Oct 24 '22 02:10

HardcoreBro