I have a class that uses .NETS SerialPort
class to communicate with a device.
I want to use Mocks to help write tests for my class, ideally I would like to create a Mock for the SerialPort
class.
I believe I can't create a mock of SerialPort
because the class has no vritual methods, is that correct?
To work around this limitation, I have created an interface and an implementation MyComPort
. Using this I'm able to implement some test. However, I would like to avoid needing to have the MyComPort
class. Is this possible?
IComPort
Interface that I will use to make the Mock.
public interface IComPort{
int ReadTimeout { get; set; }
void Open();
void Write(String data);
String ReadExisting();
int ReadChar();
void DiscardInBuffer();
}
MyComPort
Class that I use to wrap the .NET SerialPort and implement the IComPort interface.
I want to avoid needing this class. If it's not possible, I want to know if it's a good idea to make all the methods AgressiveInlining
.
public class MyComPort : SerialPort, IComPort{
public new int ReadTimeout {
get { return base.ReadTimeout; }
set { base.ReadTimeout = value; }
}
public MotorComPort(String portName, int baudrate, Parity parity, int databits, StopBits stopbits)
: base(portName, baudrate, parity, databits, stopbits) { }
public new void Open() {
base.Open();
}
public new void Write(String data) {
base.Write(data);
}
public new String ReadExisting() {
return base.ReadExisting();
}
public new int ReadChar() {
return base.ReadChar();
}
public new void DiscardInBuffer() {
base.DiscardInBuffer();
}
}
ClassThatUsesComPort
The class that uses the serial port, which is the one I want to test.
public class ClassThatUsesComPort{
private IComPort mComPort;
public ClassThatUsesComPort(IComPort cP){
mComPort = cP;
}
[...]
}
Main
The main, example of how I'm using the class I want to test.
class Program{
static void Main(...){
MyComPort mcp = new MyComPort(...);
ClassThatUsesComPort x = new ClassThatUsesComPort(mcp);
[...]
}
}