[BAEL-1858] - How to mock a static method using JMockit (#4925)

This commit is contained in:
Kartik Singla 2018-08-18 11:10:55 +05:30 committed by Grzegorz Piwowarek
parent 65fa376887
commit 9bb33102f9
2 changed files with 70 additions and 0 deletions

View File

@ -0,0 +1,26 @@
package com.baeldung.mocks.jmockit;
import java.util.Random;
public class AppManager {
public boolean managerResponse(String question) {
return AppManager.isResponsePositive(question);
}
public static boolean isResponsePositive(String value) {
if (value == null)
return false;
int orgLength = value.length();
int randomNumber = randomNumber();
return orgLength == randomNumber ? true : false;
}
private static int randomNumber() {
return new Random().nextInt(7);
}
private static Integer stringToInteger(String num) {
return Integer.parseInt(num);
}
}

View File

@ -0,0 +1,44 @@
package com.baeldung.mocks.jmockit;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import mockit.Deencapsulation;
import mockit.Mock;
import mockit.MockUp;
public class AppManagerUnitTest {
private AppManager appManager;
@BeforeEach
public void setUp() {
appManager = new AppManager();
}
@Test
public void givenAppManager_whenStaticMethodCalled_thenValidateExpectedResponse() {
new MockUp<AppManager>() {
@Mock
public boolean isResponsePositive(String value) {
return false;
}
};
Assertions.assertFalse(appManager.managerResponse("Why are you coming late?"));
}
@Test
public void givenAppManager_whenPrivateStaticMethod_thenValidateExpectedResponse() {
final int response = Deencapsulation.invoke(AppManager.class, "stringToInteger", "110");
Assertions.assertEquals(110, response);
}
@Test
public void givenAppManager_whenPrivateStaticMethod_thenExpectException() {
Assertions.assertThrows(IllegalArgumentException.class, () -> {
Deencapsulation.invoke(AppManager.class, "stringToInteger", "11r");
});
}
}