[BAEL-1858] - How to mock a static method using JMockit (#4925)
This commit is contained in:
parent
65fa376887
commit
9bb33102f9
|
@ -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);
|
||||
}
|
||||
}
|
|
@ -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");
|
||||
});
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue