It turns out that mock can be used in this way.
1. Interface iserialport
Public interface iserialport {string portname {Get;} int baudrate {Get;} int databits {Get;} parity party {Get;} 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. use rhino mock to test the serial port
[Testmethod ()] public void readalarmtest () {mockrepository mock = new mockrepository (); iserialport SerialPort = mock. strictmock <iserialport> (); vserialport target = new vserialport (SerialPort); string serialized Ted = ", 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. CT (P => P. readbyte ()). return (0x21); SerialPort. CT (P => P. write (New byte [] {1, 0x64, 0x0d}, 0, 3); SerialPort. CT (P => P. bytestoread ). return (data. length); SerialPort. CT (P => P. read (ref outdata, 0, outdata. length )). outref (data ). return (data. length); SerialPort. CT (P => P. bytestoread ). return (0);} target. readalarm (); actual = sb. tostring (); assert. areequal (specified Ted, 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 ();}