Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Designing a robust unit test - testing the same logic in several different ways?

In unit test design, it is very easy to fall into the trap of actually just calling your implementation logic.

For example, if testing an array of ints which should all be two higher than the other (2, 4, 6, 8, etc), is it really enough to get the return value from the method and assert that this pattern is the case?

Am I missing something? It does seem like a single unit test method needs to be made more robust by testing the same expectation in several ways. So the above expectation can be asserted by checking the increase of two is happening but also the next number is divisible by 2. Or is this just redundant logic?

So in short, should a unit test test the one expectation in several ways? For example, if I wanted to test that my trousers fit me, I would/could measure the length, put it next to my leg and see the comparison, etc. Is this the sort of logic needed for unit testing?

Thanks

like image 368
javacoderx Avatar asked Sep 30 '10 20:09

javacoderx


2 Answers

Your unit tests should check all of your assumptions. Whether you do that in 1 test or multiple tests is a personal preference.

In the example you stated above, you had two different assumptions: (1) Each value should increment by 2. (2) All values should be even.

Should (-8,-6,-4,-2) pass/fail?

Remember, ensuring your code fails when it's supposed to is just as important, if not more important, then making sure it passes when it's supposed to.

like image 136
Snekse Avatar answered Oct 05 '22 23:10

Snekse


If you assert that your array contains 2,4,6,8 -- then your testing logic might be flawed because your test would pass if you just returned an array with those elements, but not with, say, 6,8,10,12. You need to test that calculation is correct. So you need to test it with multiple arrays, in this particular case.

I find that making sure the test fails, then making the test pass, in the true spirit of TDD, helps flush out what the correct test is...

like image 35
hvgotcodes Avatar answered Oct 06 '22 01:10

hvgotcodes