Flushing a static method in a final class in Java / Mockito

If i have a class

public final class Application {
    public static String getName() { return "Bad App"; }
}

then how can I change the behavior and make getNamereturn, say "Good App",? I need to mock this so the tested classes get the expected value. In fact, the static method makes some kind of network call that I want to avoid.

I can not rewrite the application code.

I use Java 6, Maven, JUnit and Mockito.

Is it possible?

+4
source share
1 answer

You can do this using powermockito as shown below:

Say this is your class with a static method:

public final class MyStaticClass {
    public static String helloWorld() {
        return "Hello World";
    }
}

helloWorld "Hi World" . :

@RunWith(PowerMockRunner.class)
@PrepareForTest({MyStaticClass.class})
public class PowerMockItoTest {
    @Test
    public void mockStaticClassTest() {
        PowerMockito.mockStatic(MyStaticClass.class);
        final String mockedResult = "Hi World";
        Mockito.when(MyStaticClass.helloWorld()).thenReturn(mockedResult);
        Assert.assertEquals(AStaticClass.helloWorld(), mockedResult);
    }
}

PowerMock, , :

@RunWith(PowerMockRunner.class)
@PrepareForTest({MyStaticClass.class})
public class PowerMockTest {
    @Test
    public void testRegisterService() throws Exception {   
        PowerMock.mockStatic(MyStaticClass.class);
        final String mockedResult = "Hi World";
        expect(MyStaticClass.helloWorld()).andReturn(mockedResult);
        replay(MyStaticClass.class);
        Assert.assertEquals(AStaticClass.helloWorld(), mockedResult);
        verify(MyStaticClass.class);
    }
}
+4

All Articles