1. /*
  2. * Copyright 2001-2002,2004 The Apache Software Foundation
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. *
  16. */
  17. package org.apache.tools.ant.taskdefs.optional.junit;
  18. import java.lang.reflect.Method;
  19. import junit.framework.Test;
  20. import junit.framework.TestCase;
  21. /**
  22. * Work around for some changes to the public JUnit API between
  23. * different JUnit releases.
  24. *
  25. * @version $Revision: 1.10.2.4 $
  26. */
  27. public class JUnitVersionHelper {
  28. private static Method testCaseName = null;
  29. static {
  30. try {
  31. testCaseName = TestCase.class.getMethod("getName", new Class[0]);
  32. } catch (NoSuchMethodException e) {
  33. // pre JUnit 3.7
  34. try {
  35. testCaseName = TestCase.class.getMethod("name", new Class[0]);
  36. } catch (NoSuchMethodException e2) {
  37. // ignore
  38. }
  39. }
  40. }
  41. /**
  42. * JUnit 3.7 introduces TestCase.getName() and subsequent versions
  43. * of JUnit remove the old name() method. This method provides
  44. * access to the name of a TestCase via reflection that is
  45. * supposed to work with version before and after JUnit 3.7.
  46. *
  47. * <p>since Ant 1.5.1 this method will invoke "<code>public
  48. * String getName()</code>" on any implementation of Test if
  49. * it exists.</p>
  50. */
  51. public static String getTestCaseName(Test t) {
  52. if (t instanceof TestCase && testCaseName != null) {
  53. try {
  54. return (String) testCaseName.invoke(t, new Object[0]);
  55. } catch (Throwable e) {
  56. // ignore
  57. }
  58. } else {
  59. try {
  60. Method getNameMethod = null;
  61. try {
  62. getNameMethod =
  63. t.getClass().getMethod("getName", new Class [0]);
  64. } catch (NoSuchMethodException e) {
  65. getNameMethod = t.getClass().getMethod("name",
  66. new Class [0]);
  67. }
  68. if (getNameMethod != null
  69. && getNameMethod.getReturnType() == String.class) {
  70. return (String) getNameMethod.invoke(t, new Object[0]);
  71. }
  72. } catch (Throwable e) {
  73. // ignore
  74. }
  75. }
  76. return "unknown";
  77. }
  78. }