Java Mockito验证构造函数调用方法
我试图测试Java Mockito验证构造函数调用方法,java,unit-testing,mocking,mockito,Java,Unit Testing,Mocking,Mockito,我试图测试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
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();
}
}
我是莫基托的新手。我在中尝试了以下示例,但仍然得到了相同的错误我如何理解,通过模拟游戏类,您也可以模拟构造函数。这意味着没有运行来自实际类构造函数的代码。尝试创建一个游戏类实例而不进行模拟。实际上,您需要调用start方法,然后只有模拟才会通过时间验证 比如:: mockedGames.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
仔细想想,这是有道理的:一个新的模拟对象不应该做任何事情,除非它是绝对必需的(存根)。调用任何真正的逻辑都可能产生不希望的副作用
这就是为什么你从不嘲笑被测试的类本身
当您模拟被测类本身时,您的测试完全没有意义强>
只有模拟依赖项
您的游戏
类没有依赖项,因此您不需要任何模拟:
@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
类当前是否依赖于Hand
。我很抱歉。我在找一个简单的术语,不想把你搞糊涂。你是对的。从OO的角度来看,Game
依赖于Hand
,但是为了测试Game
你不需要知道任何关于Hand
的知识,因为Game
在内部处理一切,并提供一个无参数构造函数。从测试的角度来看,您大多数时候都希望忽略某些东西是如何工作的。你要确保它能正常工作!