1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.jdiagnose.library.junit;
17
18 import java.util.ArrayList;
19 import java.util.Collections;
20 import java.util.Enumeration;
21 import java.util.List;
22
23 import junit.framework.Test;
24 import junit.framework.TestCase;
25 import junit.framework.TestResult;
26 import junit.framework.TestSuite;
27
28 import org.jdiagnose.Diagnostic;
29 import org.jdiagnose.DiagnosticContainer;
30 import org.jdiagnose.DiagnosticException;
31 import org.jdiagnose.DiagnosticUnit;
32
33 /***
34 * @author jmccrindle
35 */
36 public class TestCaseDiagnostic implements DiagnosticContainer {
37 private List diagnostics;
38
39 private String className = null;
40
41 public TestCaseDiagnostic(String className) {
42 this.className = className;
43 this.diagnostics = getReflectedDiagnostics();
44 }
45
46 public String getName() {
47 return className;
48 }
49
50 protected List getReflectedDiagnostics() {
51 List diagnostics = new ArrayList();
52 Class testClass;
53 try {
54 testClass = Class.forName(className);
55 TestSuite suite = new TestSuite(testClass);
56 for (Enumeration testEnumeration = suite.tests(); testEnumeration
57 .hasMoreElements();) {
58 final Test test = (Test) testEnumeration.nextElement();
59 diagnostics.add(new Diagnostic() {
60 public String getName() {
61 if (test instanceof TestCase) {
62 TestCase testCase = (TestCase) test;
63 return testCase.getName();
64 }
65 return test.toString();
66 }
67
68 public void diagnose() throws DiagnosticException {
69 TestResult testResult = new TestResult();
70 test.run(testResult);
71 if (!(testResult.failureCount() == 0
72 && testResult.errorCount() == 0)) {
73
74 Enumeration errors = (Enumeration) testResult.errors();
75 Enumeration failures = (Enumeration) testResult.failures();
76
77 Throwable e = null;
78
79
80 if(errors.hasMoreElements()) {
81 e = (Throwable) errors.nextElement();
82 } else if (failures.hasMoreElements()) {
83 e = (Throwable) failures.nextElement();
84 }
85
86 throw new DiagnosticException(e);
87 }
88 }
89
90 });
91 }
92 } catch (final ClassNotFoundException cnf) {
93 diagnostics.add(new DiagnosticUnit() {
94 public void diagnoseFailure() throws Exception {
95 throw cnf;
96 }
97 });
98 }
99 return diagnostics;
100 }
101
102 public List getDiagnostics() {
103 return diagnostics;
104 }
105
106
107
108
109 public List getDiagnosticContainers() {
110 return Collections.EMPTY_LIST;
111 }
112 }