2011-02-26 95 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