How do you unit-test a method with complex input-output

Posted by Dan on Stack Overflow See other posts from Stack Overflow or by Dan
Published on 2010-06-14T02:35:31Z Indexed on 2010/06/14 2:42 UTC
Read the original article Hit count: 222

Filed under:
|

When you have a simple method, like for example sum(int x, int y), it is easy to write unit tests. You can check that method will sum correctly two sample integers, for example 2 + 3 should return 5, then you will check the same for some "extraordinary" numbers, for example negative values and zero. Each of these should be separate unit test, as a single unit test should contain single assert.

What do you do when you have a complex input-output? Take a Xml parser for example. You can have a single method parse(String xml) that receives the String and returns a Dom object. You can write separate tests that will check that certain text node is parsed correctly, that attributes are parsed OK, that child node belongs to parent etc. For all these I can write a simple input, for example

<root><child/></root>

that will be used to check parent-child relationships between nodes and so on for the rest of expectations.

Now, take a look at follwing Xml:

<root>
  <child1 attribute11="attribute 11 value" attribute12="attribute 12 value">Text 1</child1>
  <child2 attribute21="attribute 21 value" attribute22="attribute 22 value">Text 2</child2>
</root>

In order to check that method worked correctly, I need to check many complex conditions, like that attribute11 and attribute12 belong to element1, that Text 1 belongs to child1 etc. I do not want to put more than one assert in my unit-test. How can I accomplish that?

© Stack Overflow or respective owner

Related posts about unit-testing

Related posts about TDD