1 package org.apache.ojb.junit; 2 3 import junit.framework.AssertionFailedError; 4 import junit.framework.TestCase; 5 import junit.framework.TestResult; 6 7 16 public class JUnitExtensions 17 { 18 68 public static class MultiThreadedTestCase extends TestCase 69 { 70 73 private Thread threads[] = null; 74 76 private TestResult testResult = null; 77 78 81 82 public MultiThreadedTestCase(String s) 83 { 84 super(s); 85 } 86 87 90 public void interruptThreads() 91 { 92 if (threads != null) 93 { 94 for (int i = 0; i < threads.length; i++) 95 { 96 threads[i].interrupt(); 97 } 98 } 99 } 100 101 103 104 public void run(final TestResult result) 105 { 106 testResult = result; 107 super.run(result); 108 testResult = null; 109 } 110 111 113 114 protected void runTestCaseRunnables(final TestCaseRunnable[] runnables) 115 { 116 if (runnables == null) 117 { 118 throw new IllegalArgumentException ("runnables is null"); 119 } 120 threads = new Thread [runnables.length]; 121 for (int i = 0; i < threads.length; i++) 122 { 123 threads[i] = new Thread (runnables[i]); 124 } 125 for (int i = 0; i < threads.length; i++) 126 { 127 threads[i].start(); 128 } 129 try 130 { 131 for (int i = 0; i < threads.length; i++) 132 { 133 threads[i].join(); 134 } 135 } 136 catch (InterruptedException ignore) 137 { 138 System.out.println("Thread join interrupted."); 139 } 140 threads = null; 141 } 142 143 149 private void handleException(final Throwable t) 150 { 151 synchronized (testResult) 152 { 153 if (t instanceof AssertionFailedError) 154 { 155 testResult.addFailure(this, (AssertionFailedError) t); 156 } 157 else 158 { 159 testResult.addError(this, t); 160 } 161 } 162 } 163 164 170 protected abstract class TestCaseRunnable implements Runnable 171 { 172 174 175 public abstract void runTestCase() 176 throws Throwable ; 177 178 181 182 public void run() 183 { 184 try 185 { 186 runTestCase(); 187 } 188 catch (Throwable t) 189 { 190 handleException(t); 191 interruptThreads(); 192 } 193 } 194 } 195 } 196 } 197 | Popular Tags |