What's an example of a simple JUnit test case?

Tom Copeland

Say you've got a little method, getName(String path) that parses a file name from a file path. You can write a JUnit test class to feed it a path and ensure that the results are what you expected.


public class ThingTester extends TestCase
{
	public ThingTester (String name) 
	{
		super (name);
	}
	
	public static void main(String[] args) 
	{
		TestRunner.runAndWait(new TestSuite(ThingTester.class));
	}

	public void testGetName() throws Exception 
	{
	    String fileSpec = new String("c:xxxyyyzzz.txt");
	    assertEquals("zzz.txt", getName(fileSpec));
	}
}

Now compile and run ThingTester. A little dot will appear if all is well; otherwise, an assertion failure and a stack trace will let you know where the problem is. If there are no problems, you can add more test cases with long paths, files with spaces in the name, etc., etc., until you feel the method is sufficiently tested.

I've found that just taking the time to write the test cases makes my code cleaner and more usuable - I tend to think more about the edge conditions since I'm trying to think up new test cases.
0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact