自从junit4加入注解(Annotation)以后,其使用方式相对于以前版本简单了许多,这里将分别从测试用例(TestCase)和测试集(TestSuit)两个方面来说明。
一. TestCase
在TestCase方面区别主要有以下两个方面:
1. 4.x之前,测试类都必须继承TestCase类才能进行单元测试,而在4.X中则没有了这个限制;
2. 4.x之前,测试类中方法必须以test开头,而在4.x中不再强制要求每个测试方法必须以test开口,改由在方法之上增加"@Test"注解即可。
具体差异可参加如下两个示例
junit4.x之前版本
- package test;
- import org.junit.Assert;
- import junit.framework.TestCase;
- public class TestCaseSample extends TestCase{
- /**
- * 测试初始化
- */
- public void setUp() throws Exception {
- }
- /**
- * 测试方法
- *
- */
- public void testMethod1(){
- Assert.assertTrue(true);
- }
- /**
- * 测试方法
- *
- */
- public void testMethod2(){
- Assert.assertTrue(true);
- }
- /**
- *释放资源(测试结束时)
- */
- public void tearDown() throws Exception {
- }
- }
junit4.x
- package test;
- import org.junit.After;
- import org.junit.Assert;
- import org.junit.Before;
- import org.junit.Test;
- public class TestCaseSample4 {
- /**
- * 测试初始化
- */
- @Before
- public void setUp() throws Exception {
- }
- /**
- * 测试方法
- *
- */
- @Test
- public void testMethod1(){
- Assert.assertTrue(true);
- }
- /**
- * 测试方法
- *
- */
- @Test
- public void testMethod2(){
- Assert.assertTrue(true);
- }
- /**
- *释放资源(测试结束时)
- */
- @After
- public void tearDown() throws Exception {
- }
- }
从上面比较可看出,采用注解后的测试用例写起来更简单。并且,测试方法可以单独的写在任何地方,从而增加了测试的灵活性。
二 TestSuite
采用注解后的TestSuite不必再实例化TestSuite,而是通过@Suite即可直接实现测试集的建立。而且,采用注解后的TestSuite添加测试类更方便。具体差异参加如下示例:
junit4.x之前版本
- package test;
- import junit.framework.Test;
- import junit.framework.TestSuite;
- public class TestsSuite {
- public static Test suite() {
- TestSuite suite = new TestSuite("Test for test");
- //$JUnit-BEGIN$
- suite.addTestSuite(TestCaseSample.class);
- //$JUnit-END$
- return suite;
- }
- }
junit4.x
- package test;
- import org.junit.runner.RunWith;
- import org.junit.runners.Suite;
- @RunWith(Suite.class)
- @Suite.SuiteClasses({
- TestCaseSample.class
- })
- public class TestSuite4 {
- }
(文/gaoyusi4964238)
本文来源:http://blog.csdn.net/gaoyusi4964238/article/details/4782537
如果给你带来帮助,欢迎微信或支付宝扫一扫,赞一下。

