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

时间:2019-02-05 03:23:25

标签: java jmockit java-11

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

在我拥有的代码中,操纵杆的实例化如下:

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

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

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

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

我要针对的行为是这样的:

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);
        }};
    }
}

被测课程的相关部分:

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找到我尝试实现的实际实现(带有我自己的代码库的错误模拟)。

1 个答案:

答案 0 :(得分:1)

我正在使用当前设置,例如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