我在一個大的傳統的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
}
我差不多明白了。 configure()仍然需要創建一個創建真實對象的適配器,我的單元測試需要調用configure()來模擬啓動設備。所以我回到了我真正的串口問題:這部分我不明白,如何單元測試configure()並讓它仍然可以在生產代碼中使用真正的端口。 – 2011-02-26 21:10:15
@fred:你的單元測試不會*調用'configure()',它會將mocks直接注入到對象中(例如使用setter方法)。只有運行時框架纔會調用'configure()',這將創建適配器對象,而不是嘲笑。 – skaffman 2011-02-26 21:19:12