DRY, string, and unit testing

Posted by Rodrigue on Programmers See other posts from Programmers or by Rodrigue
Published on 2012-07-01T16:33:21Z Indexed on 2012/07/01 21:24 UTC
Read the original article Hit count: 214

Filed under:
|

I have a recurring question when writing unit tests for code that involves constant string values.

Let's take an example of a method/function that does some processing and returns a string containing a pre-defined constant. In python, that would be something like:

STRING_TEMPLATE = "/some/constant/string/with/%s/that/needs/interpolation/"

def process(some_param):
    # We do some meaningful work that gives us a value
    result = _some_meaningful_action()
    return STRING_TEMPLATE % result

If I want to unit test process, one of my tests will check the return value. This is where I wonder what the best solution is.

In my unit test, I can:

  1. apply DRY and use the already defined constant
  2. repeat myself and rewrite the entire string
def test_foo_should_return_correct_url():
    string_result = process()

    # Applying DRY and using the already defined constant
    assert STRING_TEMPLATE % "1234" == string_result

    # Repeating myself, repeating myself
    assert "/some/constant/string/with/1234/that/needs/interpolation/" == url

The advantage I see in the former is that my test will break if I put the wrong string value in my constant. The inconvenient is that I may be rewriting the same string over and over again across different unit tests.

© Programmers or respective owner

Related posts about unit-testing

Related posts about dry