Skip to content

Commit 9bb3310

Browse files
kartiksinglapivovarit
authored andcommitted
[BAEL-1858] - How to mock a static method using JMockit (eugenp#4925)
1 parent 65fa376 commit 9bb3310

2 files changed

Lines changed: 70 additions & 0 deletions

File tree

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package com.baeldung.mocks.jmockit;
2+
3+
import java.util.Random;
4+
5+
public class AppManager {
6+
7+
public boolean managerResponse(String question) {
8+
return AppManager.isResponsePositive(question);
9+
}
10+
11+
public static boolean isResponsePositive(String value) {
12+
if (value == null)
13+
return false;
14+
int orgLength = value.length();
15+
int randomNumber = randomNumber();
16+
return orgLength == randomNumber ? true : false;
17+
}
18+
19+
private static int randomNumber() {
20+
return new Random().nextInt(7);
21+
}
22+
23+
private static Integer stringToInteger(String num) {
24+
return Integer.parseInt(num);
25+
}
26+
}
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
package com.baeldung.mocks.jmockit;
2+
3+
import org.junit.jupiter.api.Assertions;
4+
import org.junit.jupiter.api.BeforeEach;
5+
import org.junit.jupiter.api.Test;
6+
7+
import mockit.Deencapsulation;
8+
import mockit.Mock;
9+
import mockit.MockUp;
10+
11+
public class AppManagerUnitTest {
12+
13+
private AppManager appManager;
14+
15+
@BeforeEach
16+
public void setUp() {
17+
appManager = new AppManager();
18+
}
19+
20+
@Test
21+
public void givenAppManager_whenStaticMethodCalled_thenValidateExpectedResponse() {
22+
new MockUp<AppManager>() {
23+
@Mock
24+
public boolean isResponsePositive(String value) {
25+
return false;
26+
}
27+
};
28+
29+
Assertions.assertFalse(appManager.managerResponse("Why are you coming late?"));
30+
}
31+
32+
@Test
33+
public void givenAppManager_whenPrivateStaticMethod_thenValidateExpectedResponse() {
34+
final int response = Deencapsulation.invoke(AppManager.class, "stringToInteger", "110");
35+
Assertions.assertEquals(110, response);
36+
}
37+
38+
@Test
39+
public void givenAppManager_whenPrivateStaticMethod_thenExpectException() {
40+
Assertions.assertThrows(IllegalArgumentException.class, () -> {
41+
Deencapsulation.invoke(AppManager.class, "stringToInteger", "11r");
42+
});
43+
}
44+
}

0 commit comments

Comments
 (0)