How should one unit test a function which (among other things) maps an integer to a string?

If the function were to map 0 => string0, 1 => string1, 2 => string2, should I test for each of 0, 1, and 2? Or should I just test one of these cases?

  • 5
    Get rid of the "other things" and testing will be much easier.
    – JeffO
    Jun 24, 2015 at 18:05

4 Answers 4


I suggest you have one unit test for each linearly independent path through the function. In practice, this means one test, plus an additional test for each branch.

To learn more, I suggest you read about Cyclomatic complexity (https://en.wikipedia.org/wiki/Cyclomatic_complexity)


In addition to the answer above, I'd also recommend testing out edge cases - so e.g. -1, 0, and then a large number. You could also test that passing something other than an integer makes the method behave the way it is supposed to behave.


If the function does several different things (and the description "...a function which (among other things) maps an integer to a string" indicates that yours does), you should probably divide it into several functions and test each of them separately. Then, as Daniel T. suggested, make sure to test every branch through the function(s).


How about using enums(mapper int to string) and you don't need to unit test anything.

enum Days {Sat=1, Sun, Mon, Tue, Wed, Thu, Fri};

Now let's assume your mapper is used by some method that returns different results based on the mapper. Here is how I would test it.

  1. Programatically get all the values in the mapper.
  2. Iterate through each and call your method with that value.
  3. Assert after each response.

The example above would do well if you are loading something from filesystem that corresponds to your enum values or something similar. Your situation could vary.

  • Could you explain how this would solve the problem the OP is having? For int to string, are you proposing... well, thousands? millions? of values in the enum?
    – user40980
    Jun 24, 2015 at 20:31
  • OPs problem is artificial due to reinventing the wheel. Why not to just use the tools provided to you by the language?
    – Alexus
    Jun 24, 2015 at 20:32
  • @MichaelT Well, if you are mapping thousands of strings to thousands of integers, I would say: 1) Use dictionary? 2) Revise your design, this is a very smelly code you got there. 3) Assume some pattern and use parsing.
    – Alexus
    Jun 24, 2015 at 20:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.