简体   繁体   中英

How to write unit tests for classes which use hardware resources?

I created a class which extends from the JSSC library and which uses low level communication methods (sendByte, sendString, etc.). I wanted to test it via JUnit, but I don't quite know how to do it.

For example, let's have a look at the method below:

public void openConnection() throws SerialPortException {
  serialPort.openPort();
  configureConnectionParameters(serialPort);
  configureReadListener(serialPort);
}

To ensure the method works properly, I need an actual hardware device to see if the port opens correctly and during the configuration process there were no Exceptions thrown. But playing with external resources during the unit testing is generally considered as a bad practice, so I started wondering if there are any solutions to such a problems (mocking up a hardware maybe?).

Or, do I have to unit test it at all?

You should probably change the structure of your class and inject the serialPort .

This way you can mock out the injected serial port during your unit tests and additionally create a cleaner code with less hidden dependencies.

Example:

public class PortHandler {

    private final SerialPort serialPort;

    public PortHandler(SerialPort serialPort) {
      this.serialPort = serialPort;
    }

    [...]

    public void openConnection() throws SerialPortException {
      serialPort.openPort();
      configureConnectionParameters(serialPort);
      configureReadListener(serialPort);
    }

    [...]
}

@Test
public void testShouldOpenPortOnOpenConnection()
      throws Exception {

    SerialPort mockedPort = mock(SerialPort.class);
    PortHandler portHandler = new PortHandler(mockedPort);
    portHandler.openConnection();

    verify(mockedPort, times(1)).openPort();
}

Resources:

  • Mocking framework used in example: Mockito

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM