views:

57

answers:

2

Do you prefer literal values or expressions in your Asserts in your unit tests? This little example demonstrates what I mean - please pay attention to the comments:

[Test]
public function fromXML_works() : void {
    var slideshow : Slideshow = SlideshowConverter.fromXML(xmlSample);

    // do you prefer literal value "1":
    assertEquals(slideshow.id, "1");

    // ... or an expression like this:
    assertEquals(slideshow.id, xmlSample.@id);
}


private var xmlSample : XML =
    <slideshow id="1">
     <someOtherTags />
    </slideshow>;

The nice thing about the expression is that when the XML sample changes, the unit test will not break. On the other hand, I've basically provided an implementation of one aspect of my SlideshowConverter directly in my unit test which I don't like (the test should test intent, not implementation). I can also imagine that tests using expressions will be more prone to programming errors (I could have, for example, made a mistake in my E4X expression in my test method).

What approach do you prefer? What advantage is usually more important on real world projects?

+1  A: 

Personally, I like to use constants within my tests - it ensures that the test fixtures are simple and straightforward. Plus, as you mention, it avoids programming errors in the test itself, which may hide programming errors in the real code.

Joe Enos
+1  A: 

Particularly since you've tagged this TDD: stick with literals. Writing a test before code exists to pass it, you say to yourself, "Self: if I had this function and gave it those parameters, then this is what I would get back." Where this is a very specific value. Don't hide it away; don't abstract it - just put the value into the test. It enhances the documentation value of the test as well.

Carl Manaster