@Mock和@InjectMocks的区别
2022-08-31 04:10:19
和 在 Mockito 框架中有什么区别?@Mock
@InjectMocks
和 在 Mockito 框架中有什么区别?@Mock
@InjectMocks
@Mock
创建一个模拟。 创建类的实例,并将使用 (or ) 注释创建的模拟注入到此实例中。@InjectMocks
@Mock
@Spy
注意:您必须使用 或 来初始化这些模拟并注入它们 (JUnit 4)。@RunWith(MockitoJUnitRunner.class)
Mockito.initMocks(this)
对于 JUnit 5,必须使用 .@ExtendWith(MockitoExtension.class)
@RunWith(MockitoJUnitRunner.class) // JUnit 4
// @ExtendWith(MockitoExtension.class) for JUnit 5
public class SomeManagerTest {
@InjectMocks
private SomeManager someManager;
@Mock
private SomeDependency someDependency; // this will be injected into someManager
// tests...
}
这是一个关于如何工作的示例代码。@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将模拟玩家类及其行为使用和方法。最后,使用Mockito会将其放入.when
thenReturn
@InjectMocks
Player
Game
请注意,您甚至不必创建对象。Mockito会为你注射它。new Game
// 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 将检查 Game 类,即 和 。Type Signature
Player
List<String>