`

JUnit的要点概括

阅读更多

JUnit的知识要点:

         通过注释来实现测试。

1.       before

2.       test

3.       after

4.       ignore

5.       beforeClass

6.       afterClass

7.       runwith:运行的模式选择。有默认模式,还有其他的模式。包括参数测试

8.       打包测试  1.配置runwith2.配置要运行的类

---------------------------------------------------------------

几种测试运行器的介绍:

1.默认运行器:TestClassRunner

2.参数测试 Parameterized 通过@Parametes注视来构建参数。 用static方法来构建,返回一个集合:

@Parameters

public static Collection regExValues() {
 return Arrays.asList(new Object[][] {
  {"22101", true },
  {"221x1", false },
  {"22101-5150", true },
  {"221015150", false }});
}

3.打包测试 Suite.class 注视为:

@RunWith(Suite.class)

 

@SuiteClasses({ParametricRegularExpressionTest.class,
      RegularExpressionTest.class,
      TimedRegularExpressionTest.class})
public class JUnit4Suite {

}

4.版本不和的解决方案:----------------------------选择了解()

Ant 和 JUnit 4

现在,Ant 和 JUnit 成为完美组合已久,许多开发人员预料这种关系在引入 JUnit 4 后只会变得更好。但结果是,存在一定问题。如果您正在运行 Ant 1.7 之前的任何版本,将不能轻易地运行现成的 JUnit 4 测试。那并不是说您不能运行这些测试 —— 而只是不能立刻运行这些测试。

不般配的一对

在 Ant(1.7 以前的版本)中运行 JUnit 4 测试(在清单 14 中)会产生一些有趣的结果;


清单 14. 一个简单的 JUnit 4 测试类
                    
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.assertTrue;

public class RegularExpressionTest {
 private static String zipRegEx = "^\\d{5}([\\-]\\d{4})?$";
 private static Pattern pattern;

 @BeforeClass
 public static void setUpBeforeClass() throws Exception {
  pattern = Pattern.compile(zipRegEx);
 }

 @Test
 public void verifyGoodZipCode() throws Exception{		
  Matcher mtcher = this.pattern.matcher("22101");
  boolean isValid = mtcher.matches();		
  assertTrue("Pattern did not validate zip code", isValid);
 }
}

多处失败

在 Ant 中使用脆弱的 junit 任务会导致清单 15 中的错误:


清单 15. 一堆错误
                    
[junit] Running test.com.acme.RegularExpressionTest
[junit] Tests run: 1, Failures: 1, Errors: 0, Time elapsed: 0.047 sec
[junit] Testsuite: test.com.acme.RegularExpressionTest
[junit] Tests run: 1, Failures: 1, Errors: 0, Time elapsed: 0.047 sec

[junit] Testcase: warning took 0.016 sec
[junit]     FAILED
[junit] No tests found in test.com.acme.RegularExpressionTest
[junit] junit.framework.AssertionFailedError: No tests found in
  test.com.acme.RegularExpressionTest
[junit] Test test.com.acme.RegularExpressionTest FAILED

相应的解决方案

如果想要在 Ant 1.7 版之前的版本上运行 JUnit 4 测试,必须用 suite() 方法来翻新测试用例,该方法返回一个 JUnit4TestAdapter 实例,如清单 16 所示:


清单 16. 旧方法的新用法
                    
public static junit.framework.Test suite(){
 return new JUnit4TestAdapter(RegularExpressionTest.class);
}

由于和 @Test 注释的名称相似,所以必须让这个实例中的 Test 的返回类型名称完整。一旦 suite() 方法准备就绪,任何版本的 Ant 都会愉快地运行您的 JUnit 4 测试

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics