在实际编码测试中,我们有的时候需要对一个方法进行多次测试,那么怎么办呢?这个问题和测试套件解决的方案一样,我们总不能不停的去右键run as,那怎么办呢?还好伟大的junit帮我们想到了。
OK,现在我们开始来写一个例子:
测试源码:
package org.linkinpark.junit.testjunit;
/**
* @创建作者: LinkinPark
* @创建时间: 2016年2月5日
* @功能描述: 写一个测试源码
*/
public class Linkin
{
public String test(String str)
{
return str + "。。。";
}
}
测试代码:
package org.linkinpark.junit.testjunit;
import org.junit.Assert;
import junit.extensions.RepeatedTest;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
public class LinkinTest extends TestCase
{
public LinkinTest()
{
super();
}
public LinkinTest(String name)
{
super(name);
}
public static Test suite()
{
TestSuite suite = new TestSuite();
suite.addTest(new RepeatedTest(new LinkinTest("test"), 20));
return suite;
}
public void test() throws Exception
{
Linkin test = new Linkin();
String str = test.test("LinkinPark");
Assert.assertEquals("LinkinPark。。。", str);
}
}
现在我们运行一下,然后我们看下junit控制台什么情况?
OK,测试通过,我们也看到了,我们写的这个test测试方法执行20次,现在我们既然会使用junit来进行方法的重复测试了。那么junit到底是怎么实现的呢?我在前面的junit源码解析整理中没有整理到这部分。
那我们现在一起来看一下:
上面的测试代码使用junit38测试套件,就是自定义了Suite()方法,我不知道junit4X系列中这个重复测试能不能用,个人觉得好像是不行。先言归正传吧。在我们自己定义的Suite类中,我们调用addTest()方法来添加用例,注意这里添加的是RepeatedTest类,那我们现在就来看看这个类的源码:
RepeatedTest类的父类TestDecorator源码如下:
<