Unit-testing – How to write unit tests for robots (and other mechanical devices)

unit testing

I'm a member of my high school's robotics club, and am responsible for programming the robot. One suggestion I keep hearing from various adults is that I should be writing unit tests to help validate my code. The code base is getting a bit big, and I do agree that unit tests would be really helpful in helping me catch bugs quicker.

However, I'm not entirely sure how I could accomplish this. To the best of my knowledge, unit testing is done by taking a function (or a subsystem of the code) and feeding it a set of input to make sure it comes out with the same output each time. The code that I currently have doesn't do any heavy data crunching, but rather directly manipulates the hardware components on the robot. Most of the complexity comes from making sure that the electronics are sound, that the code at the moment matches the actual hardware on the robot, etc. Often times, I can only see if there's a problem by loading the code to the robot itself, and attempting to run it.

By extension, how can unit tests be written for code meant to operate any mechanical device? It seems to me that you can only catch errors by physically observing the operation of the machine.

Or am I just misunderstanding how unit tests should work?

(If it matters, here's the code, it's written in C++, and I'm participating in FRC)

Best Answer

You will need to mock the hardware layer to do this testing. The idea is that instead of your code talking to the actual hardware, you talk to a fake version of the hardware that you can control and then use to verify that your code is working correctly.

Unfortunately there are some problems you have to overcome:

  • Mocking things in relatively low-level languages is more difficult (and thus, a lot more work)
  • Mocking hardware-level stuff is more difficult (and thus, a lot more work)

Also, most of the value of automated, unit testing comes from being able to run your tests at any time to catch regression bugs for long periods of time after you write the original code. With these sorts of competitions, your code won't be used at all after the contest is over, so you won't really get most of the value out of the tests. And considering how difficult it would be to add tests to your particular case, it might be better use of your time to just do manual testing and focus on features for the contest.

Related Topic