Junit 4.7 MethodRule

来源:互联网 发布:如何弄死一个淘宝店铺 编辑:程序博客网 时间:2024/06/07 05:27
一个MethodRule就是对测试的运行及报告方式的一种替代方案。一个测试方法可以同时实施多个不同的MethodRule。执行测试方法的Statement对象会依次传递给各个Rule注解,并且每一个规则都会返回一个替换了的或者修改过的Statement对象,并且如果存在下一个规则的话,会把这个Statement抛给它。 

并且我发现junit默认提供了下列的MethodRule,当然我们也可以写自己的: 
  • ErrorCollector : 收集一个测试方法里面的多个错误
  • ExpectedException : 对抛出的异常提供灵活的判断
  • ExternalResource : 对外部资源的操控,例如启动或者停止一个服务器
  • TemporaryFolder : 进行测试期间相关的测试操作。例如创建测试所需的临时文件,并且在测试完结之后删除它们。
  • TestName : 在测试方法中记住测试的名称
  • TestWatchman : 在方法执行的事件中添加额外的逻辑
  • Timeout : 当测试的执行超过特定时间后导致测试失败
  • Verifier : 假如对象状态不正确时让测试失败

就我经验来说,它尝试把以前的expect,timeout等标记进行了整合,并且添加了一些其它的扩展。这套规则机制除了把以前凌乱的测试扩展的控制机制统一起来之外,还允许你对测试的策略进行自定义。可见这个版本的junit更加简单并且灵活。 

MethodRule里面就只有一个方法: 
Java代码  收藏代码
  1.     Statement apply(Statement base, FrameworkMethod method, Object target);  
  2.   
  3.   
  4. 其中,base就是上面提到的执行测试方法的Statement对象,method为要执行的测试方法,target则是测试类的实例。  
  5.   
  6. 返回结果,根据javadoc的描述,当然就是一个Statement对象了。。。  
  7.   
  8. 现在我们进一步看看各个默认Rule的详细情况,它们都在org.junit.rules里面:  
  9. [img]http://dl.iteye.com/upload/attachment/182501/50591715-67ee-31c8-a19e-0c66ce7ca8d5.gif[/img]  
  10.   
  11. [b]ErrorCollector[/b]  
  12. 作用:允许你把测试过程的所有异常都交给它,然后在最后让它一次性对所有异常进行汇报。  
  13. 示例:  
  14. [code="java]  
  15. public static class UsesErrorCollectorTwice {  
  16.     @Rule  
  17.     public ErrorCollector collector= new ErrorCollector();  
  18.    
  19.     @Test  
  20.     public void example() {  
  21.         collector.addError(new Throwable("first thing went wrong"));  
  22.         collector.addError(new Throwable("second thing went wrong"));  
  23.         collector.checkThat(getResult(), not(containsString("ERROR!")));  
  24.         // all lines will run, and then a combined failure logged at the end.  
  25.     }  
  26. }  


在上面的例子里面,我们并不是像传统的做法那样直接把异常往外抛直接导致一个异常的Statement中断测试,而上放到这个ErrorCollector里面,最后通过Assert.checkThat方法一次性对结果进行判断是否通过。这种做法无疑是一个非常节省时间的进步,不再需要像以前那样无法一次性尝试走完测试才结束用例。 

ExpectedException 
作用:在测试方法里面动态控制期待抛出的异常类型甚至其内容 
示例: 
Java代码  收藏代码
  1. // These tests all pass.  
  2. public static class HasExpectedException {  
  3.     @Rule  
  4.     public ExpectedException thrown= new ExpectedException();  
  5.    
  6.     @Test  
  7.     public void throwsNothing() {  
  8.         // no exception expected, none thrown: passes.  
  9.     }  
  10.    
  11.     @Test  
  12.     public void throwsNullPointerException() {  
  13.         thrown.expect(NullPointerException.class);  
  14.         throw new NullPointerException();  
  15.     }  
  16.    
  17.     @Test  
  18.     public void throwsNullPointerExceptionWithMessage() {  
  19.         thrown.expect(NullPointerException.class);  
  20.         thrown.expectMessage("happened?");  
  21.         thrown.expectMessage(startsWith("What"));  
  22.         throw new NullPointerException("What happened?");  
  23.     }  
  24. }  


看到最后一个例子的时候,只能惊讶这个东西真是神奇。不过出于使用习惯,个人觉得还是@expect标记比较实用。不过无可非议,当我们对那些只会抛出同一个异常,但是message会根据出错的情况而发生变化的场合使用这个规则是非常好的选择。 

ExternalResource 
作用:在测试之前对外部资源进行初始化及在测试结束之后对这些资源进行清理的规则。 
示例: 
Java代码  收藏代码
  1. public static class UsesExternalResource {  
  2.     Server myServer= new Server();  
  3.    
  4.     @Rule  
  5.     public ExternalResource resource= new ExternalResource() {  
  6.         @Override  
  7.         protected void before() throws Throwable {  
  8.             myServer.connect();  
  9.         };  
  10.    
  11.         @Override  
  12.         protected void after() {  
  13.             myServer.disconnect();  
  14.         };  
  15.     };  
  16.    
  17.     @Test  
  18.     public void testFoo() {  
  19.         new Client().run(myServer);  
  20.     }  
  21. }  


个人感觉这个东西比较无聊。它要么是封装了@Before和@After,要么是封装了@BeforeClass和@AfterClass。虽然就字面理解它应该是实现了前者,但是为了让大家可以更好地理解我决定做个实验看看: 
Java代码  收藏代码
  1. package com.amway.training.junit;  
  2.   
  3. import org.junit.After;  
  4. import org.junit.AfterClass;  
  5. import org.junit.Before;  
  6. import org.junit.BeforeClass;  
  7. import org.junit.Rule;  
  8. import org.junit.Test;  
  9. import org.junit.rules.ExternalResource;  
  10.   
  11. public class ExternalResourceTest{  
  12.     @Before  
  13.     public void before()  
  14.     {  
  15.         System.out.println("Running in before()");  
  16.     }  
  17.       
  18.     @Before  
  19.     public void before2()  
  20.     {  
  21.         System.out.println("Running in before2()");  
  22.     }  
  23.       
  24.     @BeforeClass  
  25.     public static void beforeClass()  
  26.     {  
  27.         System.out.println("Running in beforeClass()");  
  28.     }  
  29.       
  30.     @Rule  
  31.     public ExternalResource resource = new ExternalResource() {  
  32.   
  33.         @Override  
  34.         protected void after() {  
  35.             System.out.println("Running in resource.after()");  
  36.         }  
  37.   
  38.         @Override  
  39.         protected void before() throws Throwable {  
  40.             System.out.println("Running in resource.before()");  
  41.         }  
  42.           
  43.     };  
  44.       
  45.     @Rule  
  46.     public ExternalResource resource2 = new ExternalResource() {  
  47.   
  48.         @Override  
  49.         protected void after() {  
  50.             System.out.println("Running in resource2.after()");  
  51.         }  
  52.   
  53.         @Override  
  54.         protected void before() throws Throwable {  
  55.             System.out.println("Running in resource2.before()");  
  56.         }  
  57.       
  58. };  
  59.       
  60.     @After  
  61.     public void After()  
  62.     {  
  63.         System.out.println("Running in after()");  
  64.     }  
  65.       
  66.     @AfterClass  
  67.     public static void AfterClass()  
  68.     {  
  69.         System.out.println("Running in afterClass()");  
  70.     }  
  71.       
  72.     @Test  
  73.     public void aTest()  
  74.     {  
  75.         System.out.println("I'm a simple test");  
  76.     }  
  77. }  


结果如我所想的一样无聊。。。 
Java代码  收藏代码
  1. Running in beforeClass()  
  2. Running in before()  
  3. Running in before2()  
  4. Running in resource2.before()  
  5. Running in resource.before()  
  6. I'm a simple test  
  7. Running in resource.after()  
  8. Running in resource2.after()  
  9. Running in after()  
  10. Running in afterClass()  


可见,它只是@Before和@After的一套替代品。不过从让@Before的执行方法和@After的执行方法一一对应这点来说,使用这个Rule来进行外部资源管理的确是一个最佳实践。因为如果我们依靠@Before和@After来实现外部资源的初始化及清理,如果只有一对组合还好,一多了就会很难搞清谁先谁后。。。。 

TemporaryFolder 
作用:帮我们在测试过程中创建特定的临时文件夹或文件用于测试,并且在测试结束后,无论是否成功,都会删除这些由它创建的东西。 
示例: 
Java代码  收藏代码
  1. public static class HasTempFolder {  
  2.     @Rule  
  3.     public TemporaryFolder folder= new TemporaryFolder();  
  4.    
  5.     @Test  
  6.     public void testUsingTempFolder() throws IOException {  
  7.         File createdFile= folder.newFile("myfile.txt");  
  8.         File createdFolder= folder.newFolder("subfolder");  
  9.         // ...  
  10.     }  
  11. }  


注意,必须通过TemporaryFolder的方法创建出来的临时文件及文件夹,才会在测试结束的时候被删除。让我们来解读一下它的代码就知道是怎么回事了: 
Java代码  收藏代码
  1. public class TemporaryFolder extends ExternalResource {  
  2.     private File folder;  
  3.   
  4.     @Override  
  5.     protected void before() throws Throwable {  
  6.         create();  
  7.     }  
  8.   
  9.     @Override  
  10.     protected void after() {  
  11.         delete();  
  12.     }  
  13.   
  14.     // testing purposes only  
  15.     /** 
  16.      * for testing purposes only.  Do not use. 
  17.      */  
  18.     public void create() throws IOException {  
  19.         folder= File.createTempFile("junit""");  
  20.         folder.delete();  
  21.         folder.mkdir();  
  22.     }  
  23.   
  24.     /** 
  25.      * Returns a new fresh file with the given name under the temporary folder. 
  26.      */  
  27.     public File newFile(String fileName) throws IOException {  
  28.         File file= new File(folder, fileName);  
  29.         file.createNewFile();  
  30.         return file;  
  31.     }  
  32.   
  33.     /** 
  34.      * Returns a new fresh folder with the given name under the temporary folder. 
  35.      */  
  36.     public File newFolder(String folderName) {  
  37.         File file= new File(folder, folderName);  
  38.         file.mkdir();  
  39.         return file;  
  40.     }  
  41.   
  42.     /** 
  43.      * @return the location of this temporary folder. 
  44.      */  
  45.     public File getRoot() {  
  46.         return folder;  
  47.     }  
  48.   
  49.     /** 
  50.      * Delete all files and folders under the temporary folder. 
  51.      * Usually not called directly, since it is automatically applied  
  52.      * by the {@link Rule} 
  53.      */  
  54.     public void delete() {  
  55.         recursiveDelete(folder);  
  56.     }  
  57.   
  58.     private void recursiveDelete(File file) {  
  59.         File[] files= file.listFiles();  
  60.         if (files != null)  
  61.         for (File each : files)  
  62.             recursiveDelete(each);  
  63.             file.delete();  
  64.     }  
  65. }  


可以看到,其实它是ExternalResource的一个子类,并且在里面有一个私有字段folder。这个字段会在before的时候通过create()方法在当前的测试类目录下被创建为junit的文件夹。并且在后续用newFolder和newFile创建目录的时候都会在此目录下进行创建。在after()推出测试方法时则会把这个folder及其子文件和文件夹通通删除。 

所以,这个规则在多线程测试模式下要慎用!!一旦你的同一个目录下有两个测试在同时执行的时候,就可能会出现资源竞争的情况导致删除出问题,甚至还会有其它死锁之类的漏洞! 

总体来说,当我们使用这个规则的时候看来是要经过自己重构才能够使用,把folder的名字用个不会重复的名称吧,是最简单的方法了。 

TestName 
作用:让测试方法可以调用到当前测试的测试名变量 
示例: 
Java代码  收藏代码
  1. public class TestNameTest {  
  2.     @Rule  
  3.     public TestName name= new TestName();  
  4.    
  5.     @Test  
  6.     public void testA() {  
  7.         assertEquals("testA", name.getMethodName());  
  8.     }  
  9.    
  10.     @Test  
  11.     public void testB() {  
  12.         assertEquals("testB", name.getMethodName());  
  13.     }  
  14. }  


很简单的一个例子。这个东西主要对于统一处理进程的日志显示会有帮助。后面的例子我们就会用到它。 

TestWatchman 
作用:一个测试过程的观察者。只会记录测试过程的关键事件,但是不会对测试造成任何影响。 
示例: 
Java代码  收藏代码
  1. public static class WatchmanTest {  
  2.     private static String watchedLog;  
  3.    
  4.     @Rule  
  5.     public MethodRule watchman= new TestWatchman() {  
  6.         @Override  
  7.         public void failed(Throwable e, FrameworkMethod method) {  
  8.             watchedLog+= method.getName() + " " + e.getClass().getSimpleName()  
  9.                     + "\n";  
  10.         }  
  11.    
  12.         @Override  
  13.         public void succeeded(FrameworkMethod method) {  
  14.             watchedLog+= method.getName() + " " + "success!\n";  
  15.         }  
  16.     };  
  17.    
  18.     @Test  
  19.     public void fails() {  
  20.         fail();  
  21.     }  
  22.    
  23.     @Test  
  24.     public void succeeds() {  
  25.     }  
  26.  }  


查看它的apply方法源码如下: 
Java代码  收藏代码
  1. public Statement apply(final Statement base, final FrameworkMethod method,Object target) {  
  2.     return new Statement() {  
  3.             @Override  
  4.             public void evaluate() throws Throwable {  
  5.                 starting(method);  
  6.                 try {  
  7.                     base.evaluate();  
  8.                     succeeded(method);  
  9.                 } catch (Throwable t) {  
  10.                     failed(t, method);  
  11.                     throw t;  
  12.                 } finally {  
  13.                     finished(method);  
  14.                 }  
  15.             }  
  16.     };  
  17. }  


可见我们可以监控4种状态: 
  • starting
  • succeeded
  • failed
  • finished


Timeout 
作用:对所有测试方法定义一个统一的timeout时间 
示例: 
Java代码  收藏代码
  1. public static class HasGlobalTimeout {  
  2.     public static String log;  
  3.    
  4.     @Rule  
  5.     public MethodRule globalTimeout= new Timeout(20);  
  6.    
  7.     @Test  
  8.     public void testInfiniteLoop1() {  
  9.         log+= "ran1";  
  10.         for (;;) {  
  11.         }  
  12.     }  
  13.    
  14.     @Test  
  15.     public void testInfiniteLoop2() {  
  16.         log+= "ran2";  
  17.         for (;;) {  
  18.         }  
  19.     }  
  20. }  


以前要在@Test里面逐个定义timeout属性,现在可以统一在这个规则里面定义。老问题又来了。如果我又在@Test里面定义timeout,又在Timeout里面定义超时时间,哪个会生效呢?我们可以先来看看以下实例实例: 
Java代码  收藏代码
  1. package com.amway.training.junit;  
  2.   
  3. import org.junit.Rule;  
  4. import org.junit.Test;  
  5. import org.junit.rules.ExternalResource;  
  6. import org.junit.rules.MethodRule;  
  7. import org.junit.rules.TestName;  
  8. import org.junit.rules.Timeout;  
  9.   
  10. public class TimeoutTest {  
  11.     @Rule  
  12.     public MethodRule timeout = new Timeout(1000);  
  13.       
  14.     @Rule  
  15.     public TestName testName = new TestName();  
  16.       
  17.     @Rule  
  18.     public MethodRule extres = new ExternalResource(){  
  19.   
  20.         @Override  
  21.         protected void after() {  
  22.             end = System.currentTimeMillis();  
  23.             System.out.println("Run time for ["+testName.getMethodName()+"] is:"+ (end-start));  
  24.             end = start = 0;  
  25.         }  
  26.   
  27.         @Override  
  28.         protected void before() throws Throwable {  
  29.             start = System.currentTimeMillis();  
  30.             end=0;  
  31.         }  
  32.           
  33.     };  
  34.       
  35.     private long start,end;  
  36.       
  37.     @Test  
  38.     public void testWithoutSpecTimeout()  
  39.     {  
  40.         for(;;){}  
  41.     }  
  42.       
  43.       
  44.     @Test(timeout=100)  
  45.     public void testWithSpecTimeout()  
  46.     {  
  47.         for(;;){}  
  48.     }  
  49. }  


结果为: 
Run time for [testWithoutSpecTimeout] is:1000 
Run time for [testWithSpecTimeout] is:109 

结果就是,具体的@Test的timeout可以改写这个统一的timeout。来看看其apply方法的源码: 
Java代码  收藏代码
  1. public Statement apply(Statement base, FrameworkMethod method, Object target) {  
  2.     return new FailOnTimeout(base, fMillis);  
  3. }  


然后再来看看FailOnTimeout这个类的evaluate方法: 
Java代码  收藏代码
  1. @Override  
  2. public void evaluate() throws Throwable {  
  3.     Thread thread= new Thread() {  
  4.         @Override  
  5.         public void run() {  
  6.             try {  
  7.                 fNext.evaluate();  
  8.                 fFinished= true;  
  9.             } catch (Throwable e) {  
  10.                 fThrown= e;  
  11.             }  
  12.         }  
  13.     };  
  14.     thread.start();  
  15.     thread.join(fTimeout);  
  16.     if (fFinished)  
  17.         return;  
  18.     if (fThrown != null)  
  19.         throw fThrown;  
  20.     Exception exception= new Exception(String.format(  
  21.                 "test timed out after %d milliseconds", fTimeout));  
  22.     exception.setStackTrace(thread.getStackTrace());  
  23.     throw exception;  
  24. }  


正如大家所见,这个东西会执行fNext.evaluate()方法,而对于Timeout规则来说,这个fNext是由之前的规则传递过来的,回忆一下我们在核心分析时讨论过的methodBlock方法,它最先封装的就是@Test标记的方法。所以当两者同时定义了不同的timeout时间时,它会以@Test定义的优先。 

Verifier 
作用:验证失败时可以控制测试直接失败。 
示例: 
Java代码  收藏代码
  1. package com.amway.training.junit;  
  2.   
  3. import junit.framework.Assert;  
  4.   
  5. import org.junit.Rule;  
  6. import org.junit.Test;  
  7. import org.junit.rules.MethodRule;  
  8. import org.junit.rules.Verifier;  
  9.   
  10. public class ErrorLogVerifier {  
  11.     private StringBuffer errorLog = new StringBuffer();  
  12.        
  13.     @Rule  
  14.     public MethodRule verifier = new Verifier() {  
  15.         @Override   
  16.         public void verify() {  
  17.             Assert.assertTrue(errorLog.length()==0);  
  18.         }  
  19.     };  
  20.           
  21.     @Test   
  22.     public void testThatWriteErrorLog() {  
  23.         errorLog.append("some error!!");  
  24.     }  
  25.       
  26.     @Test   
  27.     public void testThatWontWriteErrorLog() {  
  28.           
  29.     }  
  30. }  


结果: 
 

其实。。。除非你有必要对某种异常进行统一的验证处理,否则没必要使用这个Rule。 


转载自:http://jgnan.iteye.com/blog/551736

0 0
原创粉丝点击