我正在尝试测试 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 新手。我尝试过 Difference between @Mock and @InjectMocks 中的以下示例但我仍然遇到同样的错误
最佳答案
当您调用 Mockito.mock(SomeType.class)
时,Mockito 会动态创建该类型的子类,但为了实例化,它会使用某些技术来避免调用 super 构造函数 ( read more )。
试试这个:
public class Foobar {
public Foobar () {
throw new RuntimeException();
}
}
// Somewhere else ...
Mockito.mock(Foobar.class); // No exception will be thrown because constructor is never called
当您考虑一下时,这是有道理的:除非绝对需要( stub ),否则新的模拟对象不应该执行任何操作。调用任何实际逻辑可能会产生不良副作用。
这就是为什么你从不模拟被测试的类本身!
当您模拟被测类本身时,您的测试完全没有任何意义!
仅模拟依赖项。
您的 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();
}
关于java - Mockito 验证构造函数调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52558008/