在Mockito框架中@Mock和@InjectMocks之间有什么区别?
当前回答
@Mock注释模拟相关对象。
@InjectMocks注释允许将@Mock创建的不同(和相关的)模拟注入到底层对象中。
两者是相辅相成的。
其他回答
使用@Tom提到的方法的一个好处是,您不必在SomeManager中创建任何构造函数,从而限制客户端实例化它。
@RunWith(MockitoJUnitRunner.class)
public class SomeManagerTest {
@InjectMocks
private SomeManager someManager;
@Mock
private SomeDependency someDependency; // this will be injected into someManager
//You don't need to instantiate the SomeManager with default contructor at all
//SomeManager someManager = new SomeManager();
//Or SomeManager someManager = new SomeManager(someDependency);
//tests...
}
这是否是一个好的实践取决于你的应用程序设计。
这是一个关于@Mock和@ injectmock如何工作的示例代码。
假设我们有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类需要玩家执行攻击。
@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将使用when and thenReturn方法模拟Player类及其行为。最后,使用@InjectMocks Mockito将该玩家放入游戏中。
注意,您甚至不需要创建一个新的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将检查Game类的Type Signature,即Player和List<String>。
Mockito所基于的“Mock框架”是一个允许您创建Mock对象的框架(在旧术语中,这些对象可以称为分流,因为它们作为依赖功能的分流) 换句话说,模拟对象用于模拟代码所依赖的真实对象,您可以使用模拟框架创建代理对象。 通过在测试中使用模拟对象,基本上可以从普通的单元测试过渡到集成测试
Mockito是一个在MIT许可下发布的Java开源测试框架,它是一个“模拟框架”,可以让你用干净简单的API编写漂亮的测试。在Java领域中有许多不同的模拟框架,但是基本上有两种主要的模拟对象框架,一种是通过代理实现的,另一种是通过类重映射实现的。
像Spring这样的依赖注入框架允许您在不修改任何代码的情况下注入代理对象,模拟对象期望调用某个方法并返回预期结果。
@InjectMocks注释尝试实例化测试对象实例,并将带有@Mock或@Spy注释的字段注入到测试对象的私有字段中。
initmocks (this)调用,重置测试对象并重新初始化模拟,所以记得在@Before / @BeforeMethod注释中有这个。
@Mock注释模拟相关对象。
@InjectMocks注释允许将@Mock创建的不同(和相关的)模拟注入到底层对象中。
两者是相辅相成的。
@Mock用于创建和注入模拟实例,而无需调用Mockito。手动模拟。在本例中,实例是ClassB。
而@InjectMocks用于自动将模拟字段注入到测试对象中。在这种情况下,它将是a类