Skip to content

Commit 5258668

Browse files
rimowrim
and
rim
authored
[email protected] Mocking a Method in the Same Test Class Using Mockito Spy (#18047)
* adding spy methods * modifications following review * move to new mockito 4 module * merge in one class * remove print --------- Co-authored-by: rim <[email protected]>
1 parent e81c74d commit 5258668

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package com.baeldung.spymethods;
2+
3+
public class CatTantrum {
4+
5+
public enum CatAction {
6+
BITE,
7+
MEOW,
8+
VOMIT_ON_CARPET,
9+
EAT_DOGS_FOOD,
10+
KNOCK_THING_OFF_TABLE
11+
}
12+
public enum HumanReaction {
13+
SCREAM,
14+
CRY,
15+
CLEAN,
16+
PET_ON_HEAD,
17+
BITE_BACK,
18+
}
19+
20+
public HumanReaction whatIsHumanReaction(CatAction action){
21+
return switch (action) {
22+
case MEOW -> HumanReaction.PET_ON_HEAD;
23+
case VOMIT_ON_CARPET -> HumanReaction.CLEAN;
24+
case EAT_DOGS_FOOD -> HumanReaction.SCREAM;
25+
case KNOCK_THING_OFF_TABLE -> HumanReaction.CRY;
26+
case BITE -> biteCatBack();
27+
};
28+
}
29+
30+
public HumanReaction biteCatBack() {
31+
// Some logic
32+
return HumanReaction.BITE_BACK;
33+
}
34+
35+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import com.baeldung.spymethods.CatTantrum;
2+
import com.baeldung.spymethods.CatTantrum.CatAction;
3+
import com.baeldung.spymethods.CatTantrum.HumanReaction;
4+
import org.junit.jupiter.api.Test;
5+
import org.mockito.Mockito;
6+
7+
import static org.junit.jupiter.api.Assertions.assertEquals;
8+
import static org.mockito.Mockito.when;
9+
10+
public class CatTantrumUnitTest {
11+
12+
@Test
13+
public void givenMockMethodHumanReactions_whenCatActionBite_thenHumanReactionsBiteBack(){
14+
//Given
15+
CatTantrum catTantrum = new CatTantrum();
16+
CatTantrum catTantrum1 = Mockito.spy(catTantrum);
17+
Mockito.doReturn(HumanReaction.BITE_BACK).when(catTantrum1).biteCatBack();
18+
19+
//When
20+
HumanReaction humanReaction1 = catTantrum1.whatIsHumanReaction(CatAction.BITE);
21+
22+
//Then
23+
assertEquals(humanReaction1, HumanReaction.BITE_BACK);
24+
}
25+
26+
}

0 commit comments

Comments
 (0)