@Mock和@InjectMocks之间的区别

@Mock和@InjectMocksMockito框架有什么区别?


吃鸡游戏
浏览 4149回答 3
3回答

蓝山帝景

@Mock创建一个模拟。@InjectMocks创建该类的实例,并将使用@Mock(或@Spy)注释创建的模拟注入该实例。请注意,您必须使用@RunWith(MockitoJUnitRunner.class)或Mockito.initMocks(this)初始化这些模拟并注入它们。@RunWith(MockitoJUnitRunner.class)public class SomeManagerTest {    @InjectMocks    private SomeManager someManager;    @Mock    private SomeDependency someDependency; // this will be injected into someManager     //tests...}

红颜莎娜

这是一个关于如何一个示例代码@Mock和@InjectMocks作品。假设我们有Game和Player类。class Game {&nbsp; &nbsp; private Player player;&nbsp; &nbsp; public Game(Player player) {&nbsp; &nbsp; &nbsp; &nbsp; this.player = player;&nbsp; &nbsp; }&nbsp; &nbsp; public String attack() {&nbsp; &nbsp; &nbsp; &nbsp; return "Player attack with: " + player.getWeapon();&nbsp; &nbsp; }}class Player {&nbsp; &nbsp; private String weapon;&nbsp; &nbsp; public Player(String weapon) {&nbsp; &nbsp; &nbsp; &nbsp; this.weapon = weapon;&nbsp; &nbsp; }&nbsp; &nbsp; String getWeapon() {&nbsp; &nbsp; &nbsp; &nbsp; return weapon;&nbsp; &nbsp; }}如您所见,Game类需要Player执行attack。@RunWith(MockitoJUnitRunner.class)class GameTest {&nbsp; &nbsp; @Mock&nbsp; &nbsp; Player player;&nbsp; &nbsp; @InjectMocks&nbsp; &nbsp; Game game;&nbsp; &nbsp; @Test&nbsp; &nbsp; public void attackWithSwordTest() throws Exception {&nbsp; &nbsp; &nbsp; &nbsp; Mockito.when(player.getWeapon()).thenReturn("Sword");&nbsp; &nbsp; &nbsp; &nbsp; assertEquals("Player attack with: Sword", game.attack());&nbsp; &nbsp; }}Mockito将模拟Player类,并使用when和thenReturn方法对其行为进行模拟。最后,使用@InjectMocksMockito将其Player放入Game。注意,您甚至不必创建new Game对象。Mockito将为您注入。// you don't have to do thisGame game = new Game(player);使用@Spy注释,我们也会得到相同的行为。即使属性名称不同。@RunWith(MockitoJUnitRunner.class)public class GameTest {&nbsp; @Mock Player player;&nbsp; @Spy List<String> enemies = new ArrayList<>();&nbsp; @InjectMocks Game game;&nbsp; @Test public void attackWithSwordTest() throws Exception {&nbsp; &nbsp; Mockito.when(player.getWeapon()).thenReturn("Sword");&nbsp; &nbsp; enemies.add("Dragon");&nbsp; &nbsp; enemies.add("Orc");&nbsp; &nbsp; assertEquals(2, game.numberOfEnemies());&nbsp; &nbsp; assertEquals("Player attack with: Sword", game.attack());&nbsp; }}class Game {&nbsp; private Player player;&nbsp; private List<String> opponents;&nbsp; public Game(Player player, List<String> opponents) {&nbsp; &nbsp; this.player = player;&nbsp; &nbsp; this.opponents = opponents;&nbsp; }&nbsp; public int numberOfEnemies() {&nbsp; &nbsp; return opponents.size();&nbsp; }&nbsp; // ...这是因为Mockito将检查Type SignatureGame类的Player和List<String>。
打开App,查看更多内容
随时随地看视频慕课网APP