如果你之前没有用过JUnit,那么赶紧按照一下步骤体验一下:
以下步骤都是在Eclipse下操作的,如果你不是使用Eclipse,那么请自己适配一下。
1、新建一个Java工程
2、右键工程>properties>java build path>libraries>add library>JUNIT_HOME,选中后就可以使用JUnit了。
3、新建一个被测试的类,下面是第一部分讲的CoolClass
package org.lhj.cool.junit;
public class CoolClass
{
public CoolClass()
{
super();
}
public String reverseString(String inputStr)
{
if (null == inputStr)
{
throw new NullPointerException("Error:the input string is null.");
}
if ("".equals(inputStr))
{
return null;
}
int length = inputStr.length();
char[] outputChars = new char[length];
for (int i = 0; i < length; i++)
{
outputChars[i] = inputStr.charAt(length - i - 1);
}
return new String(outputChars);
}
public static void main(String[] args)
{
//set up the invironment
CoolClass testClass = new CoolClass();
//test the null param
try
{
testClass.reverseString(null);
System.out.println("Error:expect throw nullPointerExceptioin but not.");
}
catch (NullPointerException e)
{
System.out.println("Succeed:test the null param for reverseString succeed.");
}
//test the "" param
if (!(null == testClass.reverseString("")))
{
System.out.println("Error:expect return the null value but not.");
}
else
{
System.out.println("Succeed:test the "" param for reverseString succeed.");
}
//test the "aaAA" param
if (!"AAaa".equals(testClass.reverseString("aaAA")))
{
System.out.println("Error:expect return AAaa but not.");
}
else
{
System.out.println("Succeed:test the aaAA param for reverseString succeed.");
}
//test the "AAaa" param
if (!"aaAA".equals(testClass.reverseString("AAaa")))
{
System.out.println("Error:expect return aaAA but not");
}
else
{
System.out.println("Succeed:test the AAaa param for reverseString succeed.");
}
//the other tests...
//tear down the environment
testClass = null;
}
}
4、在CoolClass右键>new >JUnit test Case,在对话框中输入类名即可,本次输入CoolClassJTest,点击确定,便生成了测试类。
5、编辑生成的类,加入测试代码后CoolClassJTest代码如下:
package org.lhj.cool.junit.test;
import junit.framework.TestCase;
import org.lhj.cool.junit.CoolClass;
public class CoolClassJTest extends TestCase
{
private CoolClass testClass;
protected void setUp() throws Exception
{
super.setUp();
testClass = new CoolClass();
}
protected void tearDown() throws Exception
{
super.tearDown();
testClass = null;
}
public void testNullParamForReverseString()
{
try
{
testClass.reverseString(null);
fail();
}
catch (NullPointerException e)
{
}
}
public void testEmptyStringForReverseString()
{
assertNull(testClass.reverseString(""));
}
public void testSimpleParamForReverseString()
{
//test the "aaAA" param
assertEquals("AAaa", testClass.reverseString("aaAA"));
//test the "AAaa" param
assertEquals("aaAA", testClass.reverseString("AAaa"));
//the other tests...
}
}
上面用fail来进行是否抛异常的测试,如果没有抛异常就会fail;assertNull判断结果是否为null,如果不是就fail;assertEquals判断两个值是否相等。
一般常用的判断语句就以上几个,比if判断简洁多了,同时省掉了很多System.out.println语句。
6、保存后在Java编辑器右键>run as>JUnit Test
如果运行的测试都成功了,则会显示绿棒:
否则,红棒来了
在下面的failure trace你可以看到错误的原因,
双击第一行会弹出一下对话框
通过该对话框你可以知道出错的原因。