天天看點

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。