Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.