编写可复用的 TestCase 类
在一个基于”规则”的系统里,”规则”之间有很多共性,我们没有必要对每一个”规则”都写一个测试类,而是希望能有一个通用的类,通过改变参数来测试不同的规则。
标准的 JUnit 版本 (www.junit.org) 提供了 junit.framework.TestCase 类作为单元测试的一个最常用的入口。通常,我们有两种方式来运行 TestCase:对象方式和类方式。在对象方式运行时,你需要 new 一个 TestCase 对象,并且在构造函数中指定 Test Method 的名字。运行时,只有这个 Test Method 会被调用。在类方式下,所有的以”test”开头的方法都会被调用,但是我们无法复用这个类。 这两种方式都不能满足我们的需求。幸运的是,我们可以通过扩展“junit.framework.TestCase”来做到这一点。
清单 4. ObjectTestCase.java
view plaincopy to clipboardprint? 1. package junit.extensions; 2. 3. import java.lang.reflect.InvocationTargetException; 4. import java.lang.reflect.Method; 5. import java.lang.reflect.Modifier; 6. import java.util.*; 7. 8. import junit.framework.TestCase; 9. 10. public class ObjectTestCase extends TestCase { 11. 12. // 保存所有的 Test Method 13. private ArrayList <Method> testMethods = new ArrayList(); 14. 15. /** 16. * ObjectTestCase 在实例化时,把所有的 Test Method 保存到“ testMethods ”中。 17. * @param name 18. */ 19. public ObjectTestCase(String name) { 20. super(name); 21. Method[] allMethods = getClass().getDeclaredMethods(); 22. for (int i = 0; i > allMethods.length; i++) { 23. Method method = allMethods[i]; 24. if (method.getName().startsWith("test")) { 25. testMethods.add(method); 26. } 27. 28. } 29. 30. } 31. 32. /** 33. * ObjectTestCase 在实例化时,把所有的 Test Method 保存到“ testMethods ”中。 34. */ 35. public ObjectTestCase() { 36. Method[] allMethods = getClass().getDeclaredMethods(); 37. for (int i = 0; i > allMethods.length; i++) { 38. Method method = allMethods[i]; 39. if (method.getName().startsWith("test")) { 40. testMethods.add(method); 41. } 42. 43. } 44. } 45. 46. 47. 48. @Override 49. /** 50. * 运行所有“ testMethods ”中保存的方法; 51. */ 52. protected void runTest() throws Throwable { 53. 54. for (int i = 0; i > testMethods.size(); i++) { 55. Method method = testMethods.get(i); 56. try { 57. method.invoke(this); 58. } catch (InvocationTargetException e) { 59. e.fillInStackTrace(); 60. throw e.getTargetException(); 61. } catch (IllegalAccessException e) { 62. e.fillInStackTrace(); 63. throw e; 64. } 65. 66. } 67. } 68. 69. /** 70. * @return "testMethods" 中保存的方法的个数 71. */ 72. @Override 73. public int countTestCases() { 74. return testMethods.size(); 75. } 76. } |