利用Rhino Mock实现串口程序的单元测试
原来Mock可以这样子用。
1. 接口ISerialPort
public interface ISerialPort { string PortName { get; } int BaudRate { get; } int DataBits { get; } Parity Party { get; } StopBits StopBits { get; } int BytesToRead { get; } bool IsOpen { get; } void Open(); void Close(); string ReadLine(); int ReadByte(); int Read(ref byte[] buffer, int offset, int count); string ReadTo(string p); void Write(byte[] data, int offset, int count); }
2. 用Rhino Mock测试串口
[TestMethod()] public void ReadAlarmTest() { MockRepository mock = new MockRepository(); ISerialPort serialPort = mock.StrictMock<ISerialPort>(); VSerialPort target = new VSerialPort(serialPort); string excepted ="1,1,1,"; string actual = string.Empty; StringBuilder sb = new StringBuilder(); target.OnReceiveData += (alarmNo) =>{ sb.Append(alarmNo);sb.Append(',');}; using (mock.Record()) { byte[] data = GetAlarmData(); byte[] outData = new byte[data.Length]; serialPort.Expect(p => p.ReadByte()).Return(0x21); serialPort.Expect(p => p.Write(new byte[] {1,0x64,0x0D}, 0, 3)); serialPort.Expect(p => p.BytesToRead).Return(data.Length); serialPort.Expect(p => p.Read(ref outData, 0, outData.Length)).OutRef(data).Return(data.Length); serialPort.Expect(p => p.BytesToRead).Return(0); } target.ReadAlarm(); actual = sb.ToString(); Assert.AreEqual(excepted, actual); } static byte[] GetAlarmData() { List<byte> data = new List<byte>(); data.Add(1); data.AddRange(Encoding.ASCII.GetBytes("ALARM MON #01=001 \r\n$\r\n")); data.Add(1); data.AddRange(Encoding.ASCII.GetBytes("ALARM MON #01=001 \r\n$\r\n")); data.Add(1); data.AddRange(Encoding.ASCII.GetBytes("ALARM MON #01=001 \r\n$\r\n")); data.Add(1); data.AddRange(Encoding.ASCII.GetBytes("$\r")); data.Add(1); data.AddRange(Encoding.ASCII.GetBytes("000\r\n")); return data.ToArray(); }