Unit-testing – If you should only have one assertion per test; how to test multiple inputs

testingunit testing

I'm trying to build up some test cases, and have read that you should try and limit the number of assertions per test case.

So my question is, what is the best way to go about testing a function w/ multiple inputs. For example, I have a function that parses a string from the user and returns the number of minutes. The string can be in the form "5w6h2d1m", where w, h, d, m correspond to the number of weeks, hours, days, and minutes.

If I wanted to follow the '1 assertion per test rule' I'd have to make multiple tests for each variation of input? That seems silly so instead I just have something like:

self.assertEqual(parse_date('5m'), 5)
self.assertEqual(parse_date('5h'), 300)
self.assertEqual(parse_date('5d') ,7200)
self.assertEqual(parse_date('1d4h20m'), 1700)

In the one test case. Is there a better way?

Best Answer

A more pragmatic way to view the one assert per test "rule", is to have your asserts in a single test cover a single concept.

This way you are still testing a single concept in a single test. In your case, whether your input string is correctly parsed in a single date.

You should exercise your judgement on a case by case basis to check if you are better off testing a single concept with multiple asserts or having a single assert in a many tests.

Go for the option that makes for clearer tests, less repetition while still having your tests be able to highlight different points of failures in your method. You want it to be clear when a test fails exactly what happened rather than have to debug your test to find out what went wrong.