天天看点

java inject例子_java - @Mock和@InjectMocks之间的区别

这是关于new Game和thenReturn如何工作的示例代码。

假设我们有new Game和thenReturn类。

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;

}

}

如您所见,new Game类需要thenReturn才能执行@InjectMocks。

@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将使用new Game和thenReturn方法模拟Player类并且它的行为。 最后,使用@InjectMocks Mockito将Player放入Game。

请注意,您甚至不必创建new Game对象。 Mockito会为你注入它。

// you don't have to do this

Game game = new Game(player);

我们也将使用Type Signature注释获得相同的行为。 即使属性名称不同。

@RunWith(MockitoJUnitRunner.class)

public class GameTest {

@Mock Player player;

@Spy List 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 opponents;

public Game(Player player, List opponents) {

this.player = player;

this.opponents = opponents;

}

public int numberOfEnemies() {

return opponents.size();

}

// ...

那是因为Mockito将检查Game class的Type Signature,即Player和List。