我在一个大的传统的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