In the hardware world, much of the communication still happens over RS232 or RS485 serial ports. Unit testing this can be a challenge. To help with that, I’ve created a custom SerialPort wrapper, which, among other things, helps with multiple threads trying to hit the serial port at the same time. When you’re iterating over actors, this is a key bit of functionality that needs to happen.
Because I have this class injected, I can easily substitute a mock to the things that actually do serial communication. However, how do you unit test the serial component itself? System.IO.SerialPort doesn’t have an interface, so it is challenging to test.
The solution I’m using is com0com, which is essentially a null modem emulator.
There are other solutions that are also great, but they aren’t free. In particular, I was impressed by Eltima’s Virtual Serial Port Driver. I almost bought it, but couldn’t rationalize it just for automated unit tests.
To use com0com, you’ll likely need to download the signed version, unless you have driver signing turned off on your computer. Once installed, I use a simple batch file to install the desired com ports:
@echo off
cd\
cd "program files (x86)\com0com\"
"setupc.exe" --silent install PortName=COM181,EmuBR=yes,EmuOverrun=yes PortName=COM182,EmuBR=yes,EmuOverrun=yes
There are many more options, but what I needed was pretty simple. Once this is done, SerialPort connects to the virtual com port just like it’s a real com port and does its thing.
One issue I ran into is that most unit test runners run multiple tests on different threads. Since COM ports are strictly limited and only one thing can connect at a time, this can be a problem. To get around, I just made a single massive test for my serial port component.