Mocking SerialPort for unit testing

Hi all, I'm learning Rust at this moment and I'm struggling trying to mock the SerialPort trait using serialport and mockall crates:

For example I want to mock the read method:

fn create_mock_port(expected_bytes: Vec<u8>) -> Box<MockSerialPort> {
    let mut mock_port = Box::new(MockSerialPort::new());
    mock_port.expect_read()
        .returning(move |buf| {
            buf[..expected_bytes.len()].copy_from_slice(&expected_bytes);
            Ok(expected_bytes.len())
        });
    mock_port
}

And use the mock_port variable for the struct under test:

pub struct SerialPortConnector {
    port: SerialPort,
    endpoint: SerialPortEndpoint, 
}

What is the best approach to obtain my purpose?

Don't mock anything. Make your data processing code agnostic to whether it reads from a SerialPort or a ParallelPort or a UnixPipe or anything else. Reading and writing data should be generic over io::{Read, Write} types. Then you test your functions using simple byte slices or io::Cursor.

4 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.