Using regex to find JSON…from a serial port…connecting a robot’s eyes to its brain. And testing all of it with JUnit

Eventually we’re all this guy….
/^<([a-z]+)([^<]+)*(?:>(.*)<\/\1>|\s+\/>)$/

Wanna prove something in Java? Write a JUnit test.

The theory presented by our developers was: "regex is causing the processing on the roboRIO to run too slowly, regex is the problem, regex == bad"

assertTrue(matcher.find());
assertEquals(expectedStringToFind, matcher.group());
long endTime = System.currentTimeMillis();
long totalTime = endTime-startTime;
assertTrue(totalTime≤10);
  • 1. The Pattern is instantiated every time the test is run. In the wild, this would be a field level variable, instantiated at boot and therefore the processing wouldn’t pay that every time a message arrived
  • 2. It’s not testing it with any load
  • 3. It’s not testing one of our classes…it’s just testing Java (normally this would be testing the class doing the regex work and therefore be more in line with the implementation)
  • 1. The Pattern was instantiated at a TestClass level rather than within the test method (therefore only pay the cost to make it once)
  • 2. The String is recreated with Math.random() injected rather than the same string every time
  • 3. We are running this within a loop, executing it 100,000 times. If the code ever takes more than 10ms to run, the test fails.
  • Your private methods can’t be tested? Make them protected and use the same package declaration in your tests to expose them to your test suite.
  • You use a private void method for doing some processing? Stop doing that. Your method should return something, anything, that can be studied and measured.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Jamie McIlroy

Jamie McIlroy

Husband and Father. Wilderness First-Aid Certified. Terrible at tying knots. I play Squash. I like things that Trade. Leafs fan. FRC and Scouts Canada