p-unit 教程1 -- 跑最简单的测试案例

p-unit最新介绍已在developerWorks发表,请点击这里查阅

在JUnit里,写一个Test,一般的习惯是继承TestCase,而p-unit中无这要求。p-unit通过反射会收集该类的public的测试方法以及setUp/tearDown,因此和原有的JUnit test兼容。下面是一个最简单的测试案例:

public class SimpleTestClass {

public static void main(String[] args) {

new SoloRunner().run(NormalTestCass.class);

}

public void setUp() {

SampleUtil.doSomething();

}

public void tearDown() {

SampleUtil.doSomething();

}

public void testA() {

SampleUtil.doSomething();

}

public void testB() {

SampleUtil.doSomething();

}

public void testC() {

 SampleUtil.doSomething();

}

}

public class SampleUtil {
  
 private static Random _random = new Random();
 
 public static void consumeMemory(int length) {
  byte[] data = new byte[length];
  for(int i = 0, j = 0; i < data.length; ++i) {
   ++j;
  }
 }
 
 public static void consumeTime(int time) {
  ThreadUtil.sleepIgnoreInterruption(time);
 }
 
 public static void doSomething() {
  consumeTime(Math.abs(_random.nextInt()) % 500);
  consumeMemory(Math.abs(_random.nextInt()) % 100000);
 }
}

其运行结果:

[solo] Started running samples.SimpleTestClass
samples.SimpleTestClass
testA() - [29704.0bytes,348.0ms]
testB() - [18000.0bytes,118.0ms]
testC() - [81096.0bytes,470.0ms]
total: 3, failures:0 (GREEN) 1933.0ms

可以看到其内存和时间的消耗情况,测试结果 -- green :)

这是最基本的情况,接下来的变数将会在后面的文章中继续介绍。

p-unit: http://p-unit.sourceforge.net/

你可能感兴趣的:(p-unit 教程1 -- 跑最简单的测试案例)