 |
建站必读 |
 |
|
|
 |
|
 |
|
| |
| 当前位置:首页 -> 建站必读 -> .NET技术 |
|
模式与XP(好文转) |
这是Test Case在JUnit框架1.0版本中的样子(为了简化,我们忽略了注释和很多方法):
public abstract class TestCase implements Test {
private String fName;
public TestCase(String name) {
fName= name;
}
public void run(TestResult result) {
result.startTest(this);
setUp();
try {
runTest();
}
catch (AssertionFailedError e) {
result.addFailure(this, e);
}
catch (Throwable e) {
result.addError(this, e);
}
tearDown();
result.endTest(this);
}
public TestResult run() {
TestResult result= defaultResult();
run(result);
return result;
}
protected void runTest() throws Throwable {
Method runMethod= null;
try {
runMethod= getClass().getMethod(fName, new Class[0]);
} catch (NoSuchMethodException e) {
e.fillInStackTrace();
throw e;
}
try {
runMethod.invoke(this, new Class[0]);
}
catch (InvocationTargetException e) {
e.fillInStackTrace();
throw e.getTargetException();
}
catch (IllegalAccessException e) {
e.fillInStackTrace();
throw e;
}
}
public int countTestCases() {
return 1;
}
}
新的需求要求允许测试重复进行、或在它们各自的线程中进行、或以上两者。
没有经验的程序员通常在遇到这样的新需求时进行子类型化。但是在这里,因为知道TestCase对象将需要能够在同一个线程中重复运行、或在各自独立的线程中重复运行,所以程序员知道:他们需要考虑得更多。
一种实现方法是:将所有的功能都添加给TestCase本身。许多开发者——尤其是那些不了解设计模式的开发者——将会这样做,而不考虑这会使他们的类变得臃肿。他们必须添加功能,所以他们将功能添加到任何可以添加的地方。下面的代码可能就是他们的实现:
public abstract class TestCase implements Test {
private String fName;
private int fRepeatTimes;
public TestCase(String name) {
this(name, 0);
}
public TestCase(String name, int repeatTimes) {
fName = name;
fRepeatTimes = repeatTimes;
}
public void run(TestResult result) {
for (int i=0; i < fRepeatTimes; i++) {
result.startTest(this);
setUp();
try {
runTest();
}
catch (AssertionFailedError e) {
result.addFailure(this, e);
}
catch (Throwable e) {
result.addError(this, e);
}
tearDown();
result.endTest(this);
}
}
public int countTestCases() {
return fRepeatTimes;
}
}
请注意run(TestResult result)方法变大了一些。他们还为TestCase类添加了另外的构造子。到目前为止,这还不算什么大事。并且,我们可以说:如果这就是所有必须做的事情,那么使用Decorator模式就是多余的。
现在,如果要让每个TestCase对象在其自己的线程中运行又怎样呢?这里也有一个可能的实现:
public abstract class TestCase implements Test {
private String fName;
private int fRepeatTimes;
private boolean fThreaded;
public TestCase(String name) {
this(name, 0, false);
}
public TestCase(String name, int repeatTimes) {
this(name, repeatTimes, false);
}
public TestCase(String name, int repeatTimes, boolean threaded) {
fName = name;
fRepeatTimes = repeatTimes;
fThreaded = threaded;
}
public void run(TestResult result) {
if (fThreaded) {
final TestResult finalResult= result;
final Test thisTest = this;
Thread t= new Thread() {
public void run() {
for (int i=0; i < fRepeatTimes; i++) {
finalResult.startTest(thisTest);
setUp();
try {
runTest();
}
|
| |
|
| |
本站关键词: |
|
|
|
|
 |
|
 |
|