3 回答

TA貢獻1843條經驗 獲得超7個贊
@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...
}

TA貢獻1842條經驗 獲得超13個贊
這是一個關于如何一個示例代碼@Mock和@InjectMocks作品。
假設我們有Game和Player類。
class Game {
private Player player;
public Game(Player player) {
this.player = player;
}
public String attack() {
return "Player attack with: " + player.getWeapon();
}
}
class Player {
private String weapon;
public Player(String weapon) {
this.weapon = weapon;
}
String getWeapon() {
return weapon;
}
}
如您所見,Game類需要Player執行attack。
@RunWith(MockitoJUnitRunner.class)
class GameTest {
@Mock
Player player;
@InjectMocks
Game game;
@Test
public void attackWithSwordTest() throws Exception {
Mockito.when(player.getWeapon()).thenReturn("Sword");
assertEquals("Player attack with: Sword", game.attack());
}
}
Mockito將模擬Player類,并使用when和thenReturn方法對其行為進行模擬。最后,使用@InjectMocksMockito將其Player放入Game。
注意,您甚至不必創建new Game對象。Mockito將為您注入。
// you don't have to do this
Game game = new Game(player);
使用@Spy注釋,我們也會得到相同的行為。即使屬性名稱不同。
@RunWith(MockitoJUnitRunner.class)
public class GameTest {
@Mock Player player;
@Spy List<String> enemies = new ArrayList<>();
@InjectMocks Game game;
@Test public void attackWithSwordTest() throws Exception {
Mockito.when(player.getWeapon()).thenReturn("Sword");
enemies.add("Dragon");
enemies.add("Orc");
assertEquals(2, game.numberOfEnemies());
assertEquals("Player attack with: Sword", game.attack());
}
}
class Game {
private Player player;
private List<String> opponents;
public Game(Player player, List<String> opponents) {
this.player = player;
this.opponents = opponents;
}
public int numberOfEnemies() {
return opponents.size();
}
// ...
這是因為Mockito將檢查Type SignatureGame類的Player和List<String>。
添加回答
舉報