各位好:
在網路上有看到關於串列通訊用Mock測試,
程式碼如下。
範例主程式
public interface ISerialPort
{
void WriteLine(string text);
void ReadLine(string text);
}
public class MyDevice
{
private ISerialPort _port;
public MyDevice(ISerialPort port)
{
_port = port;
}
public DeviceResponse Read(...)
{
_port.WriteLine(...);
string response = _port.ReadLine();
// Parse the response.
return new DeviceResponse(response);
}
}
範例單元測試
[TestClass]
public class MyDeviceTests
{
[TestMethod]
public void Read_CheckWriteLineIsCalledWithAppropriateString()
{
Mock<ISerialPort> port = new Mock<ISerialPort>();
MyDevice device = new MyDevice(port.Object);
device.Read(...);
port.Verify(p => p.WriteLine("SpecificString"));
}
[TestMethod]
public void Read_DeviceRespondsCorrectly()
{
Mock<ISerialPort> port = new Mock<ISerialPort>();
MyDevice device = new MyDevice(port.Object);
port.Setup(p => p.ReadLine()).Returns("SomeStringFromDevice");
DeviceResponse response = device.Read(...);
// Asserts here...
}
...
}
單元測試是使用Mock,就是假定有連到串列埠,去吐資料回來。
可是這份程式,看起來要連接實體的Comport好像不行。
SerialPort My_SerialPort;
My_SerialPort = new My_SerialPort($"COM1", BaudRate);
My_SerialPort.Open();
想請問說要怎修改才能夠連接到網路程式碼的ISerialPort
傳入到主程式,可是做通訊也可以做Mock單元測試。
如有問題,在煩請各位請教
謝謝