[英]Mockito verify constructor calls method
我試圖測試何時實例化Game
類,調用start
方法。 但是我收到以下錯誤:
Wanted but not invoked:
game.start();
Actually, there were zero interactions with this mock.
我有以下課程叫做Game
public class Game {
private Hand player_hand;
private Hand dealer_hand;
public static Boolean isInPlay;
public Game() {
player_hand = new Hand();
dealer_hand = new Hand();
start();
}
public void start() {
isInPlay = true;
player_hand.hit();
player_hand.hit();
System.out.println("Player hand: ");
player_hand.printHands();
instantWinLose();
dealer_hand.hit();
dealer_hand.hit();
}
}
我有一個稱為GameTest
的測試類
@RunWith(MockitoJUnitRunner.StrictStubs.class)
public class GameTest {
@InjectMocks
Game game;
@Mock
Hand hand;
@Test
public void testGameConstruction() {
Game mockedGame = mock(Game.class);
verify(mockedGame, times(1)).start();
}
}
我是Mockito的新手。 我已經嘗試過@Mock和@InjectMocks之間的區別中的以下示例,但是我仍然遇到相同的錯誤
實際上,您需要調用start方法,然后只有時間才能驗證您的模擬。
像:: :: kededGames.start()
然后只有它的電話將被驗證
當您調用Mockito.mock(SomeType.class)
,Mockito將為該類型動態創建一個子類,但是為了進行實例化,它使用某些技術來避免調用超級構造函數(請參閱更多信息 )。
嘗試這個:
public class Foobar {
public Foobar () {
throw new RuntimeException();
}
}
// Somewhere else ...
Mockito.mock(Foobar.class); // No exception will be thrown because constructor is never called
當您考慮它時,這是有道理的:除非絕對需要,否則新的模擬對象不應執行任何操作(存根)。 調用任何實際邏輯都可能會產生不良后果。
這就是為什么您永遠不會嘲笑被測類的原因!
當您模擬被測類本身時,您的測試完全沒有任何意義!
僅模擬依賴項。
您的Game
類沒有依賴項,因此您不需要任何模擬:
@Test
public void testGameConstruction() {
Game game = new Game();
assertTrue(game.isInGame());
}
如果Game
具有依賴性,例如Hand
,則可以添加構造函數參數:
public Game (Hand hand1, Hand hand2) { .... }
接着:
@Test
public void testGameConstruction() {
Hand handMock1 = Mockito.mock(Hand.class);
Hand handMock2 = Mockito.mock(Hand.class);
Game game = new Game(handMock1, handMock2);
verify(handMock1, times(1)).hit();
verify(handMock2, times(1)).hit();
}
我的理解是,通過模擬Game類,您還可以模擬構造函數。 這意味着沒有運行來自實際類構造器的代碼。 嘗試創建Game類的實例而不進行模擬。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.