java - 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 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/

相关文章:

java - 如何将值传递给此构造函数?

java - 在数组中搜索与其他数字不同的数字

c# - 单元测试预期在 MSTest 上调用异步操作时抛出异常

java - 测试 : is there a framework allowing embedding Tomcat to simulate request/response cycles without involving HTTP?

java - 为什么我要使用 MockWebServer 而不是 WireMock?

java - 我们可以模拟第三方对象的创建或调用吗?

c# - C#中获取属性setter的方法名

java - android.graphics.Bitmap.sameAs 在 android O 中,当比较 2 个位图相同的配置、尺寸、像素数据时不返回 true

java - 受影响的行数, SQL

c# - 如何单元测试使用中断对话框取消返回到 MainDialog 的对话框