1

我正在开发一个大型遗留 Java 应用程序。它已经有一个广泛的现有框架来处理设备驱动程序。我需要为通过 JavaComm 连接到串行端口的设备创建一个新的设备驱动程序。

现有驱动程序只需在其configure()方法中创建新的串行端口,然后从串行端口对象创建新的输入和输出流,然后将这些输入和输出流用于设备通信,但没有单元测试。

但是,我希望我的新类是可单元测试的,但不确定如果它要适合这个现有的框架,该框架将期望在configure()方法中设置串行端口、输入和输出流,我该怎么做。

有任何想法吗?


    public void configure()
    {
        super.configure();

        if (isEmulated()) {
            return;
        }
        if (isFaulty()) {           
            if (isOutOfService()) {
                ZBopNotificationManager.getInstance().add(
                        new SystemNotice(SeverityCode.LEVEL3, getName(), getErrorMessage()));
            }
            return;         
         }

        // ZP:
        String portName = getSerialPort();
        // String portName = "COM1";
        try {
            CommPortIdentifier id = CommPortIdentifier.getPortIdentifier(portName);
            Trace.log(this, Trace.D, "Port name = " + id.getName());
            port = (SerialPort) id.open(getName(), 1000);
        } catch (NoSuchPortException nspe) {
            report(SeverityCode.LEVEL3, getName(), "Bar Code Scanner is not connected to " + portName + " port, or the port does not exist.");
            return;
        } catch (PortInUseException piue) {
            report(SeverityCode.LEVEL3, getName(), portName + " port is already in-use by some other device. Reason: " + piue.getMessage());
            return;
        }

        try {
            port.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
        } catch (UnsupportedCommOperationException e) {
            // this should not happen
            port.close();
            report(SeverityCode.LEVEL2, getName(), portName + " port configuration failed: " + e);
            return;
        }

        try {
            in = port.getInputStream();
            out = port.getOutputStream();
        } catch (IOException ioe) {
            port.close();
            report(SeverityCode.LEVEL3, getName(), portName + " port configuration failed: " + ioe.getMessage());
            return;
        }
meout(30);

        // ... other init code omitted
    }


4

2 回答 2

3

从表面上看,javax.commAPI 并没有让单元测试变得容易——它在类上很重要,在接口上很轻。

我的建议是为javax.comm您需要在驱动程序中使用的每个类创建接口和适配器类。然后,您的驱动程序代码将与这些接口对话,而不是直接与javax.comm. 无论如何,您可能只需要 API 的一个子集,定义这些接口应该可以帮助您阐明您的设计。

这将允许您在单元测试中使用这些接口的模拟实现(例如 JMock、Mockito 等)。您的单元测试可以将这些模拟注入驱动程序对象。

当实际使用时,驱动程序的configure()方法可以实例化适配器类而不是模拟。

于 2011-02-26T18:06:54.500 回答
1

如果我理解正确,您想测试设备驱动程序而不是使用设备驱动程序的模块。

可以进行集成测试而不是单元测试吗?如果您将串行端口-s rxdata 与 txdatapin 连接,将 rts 与 cts 引脚连接,则集成测试可以检查发送到输出流的所有内容是否应被输入流接收。

于 2011-02-26T18:58:16.907 回答