Natural Order Development

Copyright © 2008 by Leeland Artra
You are not logged in.
Login
Register



A Django site.
Blog >> Side Notes >> Unit Testing Java

Unit Testing Java

2010-07-20 10:57:24

Basic testing patterns are important. But it is also important to properly plan the testing. Building a matrix really helps make sure you are covering all the basis.

A simple case is something that will compare two items for you. These little helper classes need to be built all the time for sorted lists and other such uses. However, it is amazingly easy to get something out of alignment. So for argument sake lets stick with something simple: "Compare two strings as being equal, allowing nulls to be used such that 2 nulls return true."

So the comparison for these would be based off of this matrix:

[table]
[tr] [td]Input 1[/td] [td]Input 2[/td] [td]Result[/td] [/tr]
[tr] [td]null[/td] [td]null[/td] [td]true[/td] [/tr]
[tr] [td]"A"[/td] [td]null[/td] [td]false[/td] [/tr]
[tr] [td]null[/td] [td]"B"[/td] [td]false[/td] [/tr]
[tr] [td]"A"[/td] [td]"B"[/td] [td]false[/td] [/tr]
[tr] [td]"A"[/td] [td]different "A"[/td] [td]true[/td] [/tr]
[/table]

Now you might think that was the end of it. However, now it is important to examine the implementation.

The question is should "A" == "A" be allowed? Maybe yes maybe no. Lets assume we want the answer to be no (we do not want to allow the same object to be considered equal to itself).

Therefore, we need to add one more test to the plan, specifically:

[table]
[tr] [td]Input 1[/td] [td]Input 2[/td] [td]Result[/td] [/tr]
[tr] [td]"A"[/td] [td]same object "A"[/td] [td]false[/td] [/tr]
[/table]

assertTrue(equalsAllowNull(null, null));
assertFalse(equalsAllowNull(null, "A"));
assertFalse(equalsAllowNull("A", null));
assertFalse(equalsAllowNull("A", "B"));
// new() to prevent compiler from reusing same instance...
assertTrue(equalsAllowNull("A", new String("A"))); 
// confirm compiler is not reusing the object "A" using .equals and not ==
assertFalse("A" == new String("A"));
assertTrue("A" == "A");
// confirm the function using .equals and not ==
assertFalse(equalsAllowNull("A", "A"));


And now the actual function:

public boolean equalAllowNull(String a, String b) {

  return a == null ? b == null : a == b ? false : a.equals(b);

}



Posted by Leeland

Assigned Tags: Java, unit testing, testing

0 Comments
Comments:


Page: 1



Please login to post a reply.



Powered by Sphene Community Tools