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

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

For example, let's look at the following method:

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

To make sure that the method works correctly, I need the hardware device to display whether the port is open correctly and there are no exceptions during the configuration process. But playing with external resources during unit testing is usually considered bad practice, so I began to wonder if there are any solutions to such problems (for example, to mock equipment?).

Or do I even need a unit test?

+4
source share
1 answer

You should probably restructure your class and introduce serialPort.

This way you can make fun of an embedded serial port during unit tests and additionally create 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:

  • Hiding structure used in the example: Mockito
+4
source

Source: https://habr.com/ru/post/1664648/


All Articles