junit测试延伸--方法的重复测试

本文介绍了如何在JUnit中对同一个测试方法进行多次执行,通过创建自定义的Suite类和使用RepeatedTest。详细解析了RepeatedTest类的源码,展示了其通过循环调用来实现测试重复执行的机制。此外,还提及了TestSetup类的作用,用于测试用例的初始化和清理操作。
摘要由CSDN通过智能技术生成

在实际编码测试中,我们有的时候需要对一个方法进行多次测试,那么怎么办呢?这个问题和测试套件解决的方案一样,我们总不能不停的去右键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源码如下:
<

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值