Skip to content

Instantly share code, notes, and snippets.

@bjpeterdelacruz
Last active April 25, 2018 23:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bjpeterdelacruz/be90afff2a80103bcaa314bd4597334c to your computer and use it in GitHub Desktop.
Save bjpeterdelacruz/be90afff2a80103bcaa314bd4597334c to your computer and use it in GitHub Desktop.
How to mock static methods using PowerMockito
package com.bjpeter.sampleapp.utils;
import com.bjpeter.sampleapp.services.ServiceLoader;
import com.bjpeter.sampleapp.services.TextService;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
@PrepareForTest(ServiceLoader.class)
public class WebUtilsTest {
@Test
public void testSafeReturnUri() {
// Set up mocks.
PowerMockito.mockStatic(ServiceLoader.class);
TextService service = Mockito.mock(TextService.class);
Mockito.when(ServiceLoader.getTextService()).thenReturn(service); // getTextService() is a static method
String expectedReturnUrl = "https://www.bjpeter.com";
Mockito.when(service.getEnvText("secure.application.url")).thenReturn(expectedReturnUrl);
// Now write unit tests.
expectedReturnUrl = "https://www.bjpeter.com";
String testUrl = "https://r87.com/?http://www.bjpeter.com/";
// safeReturnUri() calls ServiceLoader.getTextService().getEnvText()
String actualReturnUrl = WebUtils.safeReturnUri(testUrl, false);
Assert.assertEquals(actualReturnUrl, expectedReturnUrl);
expectedReturnUrl = "https://www.bjpeter.com";
testUrl = "www.bjpeter.com";
actualReturnUrl = WebUtils.safeReturnUri(testUrl, false);
Assert.assertEquals(actualReturnUrl, expectedReturnUrl);
expectedReturnUrl = "https://www.bjpeter.com";
testUrl = "http://www.bjpeter.com";
actualReturnUrl = WebUtils.safeReturnUri(testUrl, false);
Assert.assertEquals(actualReturnUrl, expectedReturnUrl);
expectedReturnUrl = "https://www.bjpeter.com";
testUrl = "https://www.bjpeter.com";
actualReturnUrl = WebUtils.safeReturnUri(testUrl, false);
Assert.assertEquals(actualReturnUrl, expectedReturnUrl);
expectedReturnUrl = "https://www.bjpeter.com/welcome.html";
testUrl = "https://www.bjpeter.com/welcome.html";
actualReturnUrl = WebUtils.safeReturnUri(testUrl, false);
Assert.assertEquals(actualReturnUrl, expectedReturnUrl);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment