Should a Unit-test replicate functionality or Test output?

Posted by Daniel Beardsley on Stack Overflow See other posts from Stack Overflow or by Daniel Beardsley
Published on 2010-03-20T08:02:43Z Indexed on 2010/03/20 8:11 UTC
Read the original article Hit count: 310

I've run into this dilemma several times. Should my unit-tests duplicate the functionality of the method they are testing to verify it's integrity? OR Should unit tests strive to test the method with numerous manually created instances of inputs and expected outputs?

I'm mainly asking the question for situations where the method you are testing is reasonably simple and it's proper operation can be verified by glancing at the code for a minute.

Simplified example (in ruby):

def concat_strings(str1, str2)
  return str1 + " AND " + str2
end

Simplified functionality-replicating test for the above method:

def test_concat_strings
  10.times do
    str1 = random_string_generator
    str2 = random_string_generator
    assert_equal (str1 + " AND " + str2), concat_strings(str1, str2)
  end
end

I understand that most times the method you are testing won't be simple enough to justify doing it this way. But my question remains; is this a valid methodology in some circumstances (why or why not)?

© Stack Overflow or respective owner

Related posts about unit-testing

Related posts about testing