2011-02-26 55 views
1

我在一个大的传统的Java应用程序工作的依赖。它已经有一个广泛的现有框架来处理设备驱动程序。我需要为通过JavaComm连接到串行端口的设备创建新的设备驱动程序。咨询,类测试Java具有串口

现有驱动程序只是在其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 
    } 

 

回答

3

通过对事物的外表,在javax.comm API不会使生活方便的单元测试 - 这是上大课,和光接口上。

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

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

当用于真实的,驾驶员的configure()方法可以实例化的适配器类,而不是嘲笑。

+0

我差不多明白了。 configure()仍然需要创建一个创建真实对象的适配器,我的单元测试需要调用configure()来模拟启动设备。所以我回到了我真正的串口问题:这部分我不明白,如何单元测试configure()并让它仍然可以在生产代码中使用真正的端口。 – 2011-02-26 21:10:15

+0

@fred:你的单元测试不会*调用'configure()',它会将mocks直接注入到对象中(例如使用setter方法)。只有运行时框架才会调用'configure()',这将创建适配器对象,而不是嘲笑。 – skaffman 2011-02-26 21:19:12

1

如果我理解正确的话,你要测试devicedriver,而不是使用该设备驱动程序的模块。

它是确定有一个integrationtest,而不是一个单元测试?如果您将串行端口的rxdata与txdatapin以及带有cts引脚的rts连接起来,那么集成测试可以检查输入流应该接收到发送到输出流的每件东西。

+0

在我的情况下,我需要一个单元测试。然而,集成测试是一个很好的建议。 – 2011-02-26 21:11:05