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条经验 获得超12个赞
这是一个关于如何一个示例代码@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>。
添加回答
举报