[問題] 單元測試的串列通訊問題
各位好:
在網路上有看到關於串列通訊用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單元測試。
如有問題,在煩請各位請教
謝謝
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 114.26.44.4 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/C_Sharp/M.1590655976.A.690.html
→
05/28 18:41,
4年前
, 1F
05/28 18:41, 1F
→
05/28 20:33,
4年前
, 2F
05/28 20:33, 2F
→
05/28 20:33,
4年前
, 3F
05/28 20:33, 3F
→
05/28 20:33,
4年前
, 4F
05/28 20:33, 4F
→
05/29 00:21,
4年前
, 5F
05/29 00:21, 5F
→
05/29 09:33,
4年前
, 6F
05/29 09:33, 6F
→
05/29 09:36,
4年前
, 7F
05/29 09:36, 7F
→
05/29 09:39,
4年前
, 8F
05/29 09:39, 8F
→
05/29 09:40,
4年前
, 9F
05/29 09:40, 9F
→
05/29 09:40,
4年前
, 10F
05/29 09:40, 10F
→
05/29 09:41,
4年前
, 11F
05/29 09:41, 11F
推
05/31 01:40,
4年前
, 12F
05/31 01:40, 12F
→
05/31 01:40,
4年前
, 13F
05/31 01:40, 13F
→
05/31 21:34,
4年前
, 14F
05/31 21:34, 14F
→
05/31 21:34,
4年前
, 15F
05/31 21:34, 15F
→
05/31 21:35,
4年前
, 16F
05/31 21:35, 16F
C_Sharp 近期熱門文章
PTT數位生活區 即時熱門文章