Skip to content

Commit f92aa19

Browse files
sirishrenukumarmaibin
authored andcommitted
Mocking and verification of private methods using PowerMock (eugenp#2756)
1 parent 3096362 commit f92aa19

2 files changed

Lines changed: 78 additions & 0 deletions

File tree

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package com.baeldung.powermockito.introduction;
2+
3+
class LuckyNumberGenerator {
4+
5+
public int getLuckyNumber(String name) {
6+
7+
record(name);
8+
9+
if (name == null) {
10+
return getDefaultLuckyNumber();
11+
}
12+
13+
return getLuckyNumber(name.length() + 1);
14+
}
15+
16+
private void record(String name) {
17+
}
18+
19+
private int getDefaultLuckyNumber() {
20+
return 100;
21+
}
22+
23+
private int getLuckyNumber(int length) {
24+
return length < 5 ? 5 : 10000;
25+
}
26+
27+
}
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
package com.baeldung.powermockito.introduction;
2+
3+
import static org.junit.Assert.assertEquals;
4+
import static org.powermock.api.mockito.PowerMockito.doReturn;
5+
import static org.powermock.api.mockito.PowerMockito.spy;
6+
import static org.powermock.api.mockito.PowerMockito.verifyPrivate;
7+
import static org.powermock.api.mockito.PowerMockito.when;
8+
9+
import org.junit.Test;
10+
import org.junit.runner.RunWith;
11+
import org.mockito.ArgumentMatchers;
12+
import org.powermock.core.classloader.annotations.PrepareForTest;
13+
import org.powermock.modules.junit4.PowerMockRunner;
14+
15+
@RunWith(PowerMockRunner.class)
16+
@PrepareForTest(fullyQualifiedNames = "com.baeldung.powermockito.introduction.LuckyNumberGenerator")
17+
public class LuckyNumberGeneratorTest {
18+
19+
@Test
20+
public final void givenPrivateMethodWithReturn_whenUsingPowerMockito_thenCorrect() throws Exception {
21+
LuckyNumberGenerator mock = spy(new LuckyNumberGenerator());
22+
23+
when(mock, "getDefaultLuckyNumber").thenReturn(300);
24+
25+
int result = mock.getLuckyNumber(null);
26+
27+
assertEquals(300, result);
28+
}
29+
30+
@Test
31+
public final void givenPrivateMethodWithArgumentAndReturn_whenUsingPowerMockito_thenCorrect() throws Exception {
32+
LuckyNumberGenerator mock = spy(new LuckyNumberGenerator());
33+
34+
doReturn(1).when(mock, "getLuckyNumber", ArgumentMatchers.anyInt());
35+
36+
int result = mock.getLuckyNumber("Jack");
37+
38+
assertEquals(1, result);
39+
}
40+
41+
@Test
42+
public final void givenPrivateMethodWithNoArgumentAndReturn_whenUsingPowerMockito_thenCorrect() throws Exception {
43+
LuckyNumberGenerator mock = spy(new LuckyNumberGenerator());
44+
45+
int result = mock.getLuckyNumber("Tyranosorous");
46+
47+
verifyPrivate(mock).invoke("record", ArgumentMatchers.anyString());
48+
assertEquals(10000, result);
49+
}
50+
51+
}

0 commit comments

Comments
 (0)