标签:junit4.8.2 源代码
Runner.sort、Request.sortWith和Sorter.apply
yqj2065都快被它们搞死了。
Sorter.apply()、Request.sortWith()和Sortable.sort()三者做一件事情?为什么呢?
java.util.Comparator接口是一个策略类,定义了int compare(T o1, T o2)方法。org.junit.runner.manipulation.Sorter implements Comparator<Description>,但是Sorter仅仅是形式上的实现类。通过构造器注入的方式Sorter(Comparator<Description>comparator),初始化Sorter封装的一个实际的排序器Comparator<Description>fComparator。
而且@Override public intcompare(Description o1, Description o2)以实际排序器的返回作为返回。
好吧,这是什么设计模式我不太清楚,总之有一定道理。真正不懂的是Sorter的方法apply,这个什么时候才有用?
publicvoid apply(Object object) { if(object instanceof Sortable) { Sortablesortable = (Sortable) object; sortable.sort(this); } }接口Sortable定义的唯一的方法public void sort(Sortersorter)。而Sortable是一些Runner的父接口,也就是说,Sortable对象是具有排序方式运行测试的Runner。按照我目前的直观感觉,Sortable.sort(Sorter)不如叫Sortable.setSorter(Sorter),某些Runner如ParentRunner,应该有两个域SortStyle和FilterStyle,而不是implements它们,这样更容易理解?
现在有实际排序器:
package myTest.sort; import java.util.Comparator; import org.junit.runner.Description; public class AlphabetComparator implements Comparator<Description> { @Override public int compare(Description d1, Description d2) { return d1.getMethodName().compareTo(d2.getMethodName()); }有测试目标
package myTest.sort; import static tool.Print.*; import org.junit.*;//Test/Ignore public class Unit4{ @Test public void a() { pln("a() method executed."); } @Test @Ignore public void b() { pln("b() method executed."); } @Test public void c() { pln("c() method executed."); throw new RuntimeException("Throw delibrately"); } @Test public void f() { pln("f() method executed."); } }然后呢?茴香豆的茴有3种写法?不明就里。
package myTest.sort; import org.junit.runners.BlockJUnit4ClassRunner; import org.junit.runners.model.InitializationError; import org.junit.runner.notification.*; import org.junit.runner.*; import org.junit.runner.manipulation.Sorter; public class SortDemo { public static void t1() { BlockJUnit4ClassRunner runner=null ; try { runner= new BlockJUnit4ClassRunner(Unit4.class); //runner.filter(new MethodNameFilter("testFilteredOut")); } catch (InitializationError e) { } runner.sort(new Sorter(new AlphabetComparator())); runner.run(new RunNotifier()); } public static void t2() { Request request = Request.aClass( Unit4.class ); request = request.sortWith(new AlphabetComparator()); Runner runner = request.getRunner(); runner.run(new RunNotifier()); } public static void t3() { Request request = Request.aClass( Unit4.class ); Runner runner = request.getRunner(); Sorter sorter=new Sorter(new AlphabetComparator()); sorter.apply(runner); runner.run(new RunNotifier()); } public static void go(){t1() ;t2() ;t3(); } }
标签:junit4.8.2 源代码
原文地址:http://blog.csdn.net/yqj2065/article/details/40049373