|
| 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