如何使用 JMockit 中的给定构造函数对模拟 类 的特定实例进行验证?

How to make verifications on specific instances of mocked classes with a given constructor in JMockit?

我一直在使用 JMockit 来模拟机器人的依赖项(例如传感器、操纵杆等)。对于我的 classes 测试之一,我需要模拟两个操纵杆对象。

在我的代码中,操纵杆是这样实例化的:

Joystick joystick1 = new Joystick(0);
Joystick joystick2 = new Joystick(1);

我一直在阅读如何匹配 Instance matching section in the JMockit documentation 中的特定对象实例。

然而,这些步骤似乎不适用于验证(或者我做错了)或者它们涉及在每个测试方法的参数中使用 @Mocked 标记,这会很麻烦事实上,我希望这种行为能够进行整个 class 的几个测试。

我不能简单地将模拟实例注入到测试的 class 中,因为测试的 class 实际上是从应用程序中的另一个 class 接收它们的,我不想模拟我的实例自己的代码库,以便传递可注入的操纵杆。

我的目标行为是这样的:

public class ClassUsingJoysticksTest {
    @Injectable
    private Joystick joystick1;

    @Injectable
    private Joystick joystick2;

    @Before
    public void setUp() {
        new Expectations() {{
            new Joystick(0);
            result = joystick1;

            new Joystick(1);
            result = joystick2;
        }};
    }

    @Test
    public void someTest() {
        ClassThatUsesJoysticks classThatUsesJoysticks = new ClassThatUsesJoysticks();
        classThatUsesJoysticks.doSomething();

        new Verifications() {{
            joystick1.setRumble(1D);
            joystick2.setRumble(2D);
        }};
    }
}

被测class的相关部分:

public class ClassThatUsesJoysticks {
    public void doSomething() {
        Joystick joystick1 = OI.getInstance().getJoystick1(); // OI is our own class.
        Joystick joystick2 = OI.getInstance().getJoystick2();

        joystick1.setRumble(1);
        joystick2.setRumble(2);
    }
}

// OI class that we used to keep track of operator interface.
public class OI {
    private Joystick joystick1, joystick2;

    public OI() {
        joystick1 = new Joystick(0); // First joystick is always on port 0.
        joystick2 = new Joystick(1); // Next joystick is port 1.
    }

    public Joystick getJoystick1() {
        return joystick1;
    }

    public Joystick getJoystick2() {
        return joystick2;
    }
}

使用 JMockit 可以实现这样的功能吗?

如果你愿意,可以找到我试图实现的实际实现(使用我自己的代码库的糟糕模拟)here

我在当前设置下使用它,因为 documented

public class ClassUsingJoysticksTest {
    @Mocked Joystick joystick1;
    @Mocked Joystick joystick2;

    @Before
    public void setUp() {
        new Expectations() {
            new Joystick(0);
            result = joystick1;

            new Joystick(1);
            result = joystick2;
        }
    }

    @Test
    public void testRumbles() {
        classThatUsesJoysticks.doSomething();

        new Verifications() {{
             joystick1.setRumble(1.0);
             joystick2.setRumble(1.0);
        }};
    }
}

如果您想查看实际实现,代码为 here