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。这个什么时候才实用?(注:SortingRequest中用了一下)
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它们。这样更easy理解?
如今有实际排序器:
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(); }
}
先记录一下。
版权声明:本文博客原创文章。博客,未经同意,不得转载。