Here is a small solution:
Here is the class you want to test:
package mTTest; public class UUT { String message = null; synchronized void push(String msg){ while (null != message) { try { wait(); } catch (InterruptedException e) { } } message = msg; notifyAll(); } synchronized String pop(){ while (null == message) { try { wait(); } catch (InterruptedException e) { } } String ret = message; message = null; notifyAll(); return ret; } }
Here is the Test class. This will be called by the bz JUnit framework. Rewrite the multiTest () method. mTTest package;
import static org.junit.Assert.assertEquals; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.ListIterator; import org.junit.Test; public class DUTTest { private static List<AssertionError> errors; static void handle(AssertionError err){ errors.add(err); } @Test public void testSingle() { UUT dut = new UUT(); dut.push("hello"); assertEquals("set-get", "hello", dut.message); } @Test public void testMulti() throws Exception { errors = Collections.synchronizedList(new ArrayList<AssertionError>()); UUT dut = new UUT(); MyTestThread th = new MyTestThread(dut); dut.push("hello"); assertEquals("set-get", "hello", dut.message); th.start(); dut.push("hello"); th.join(); ListIterator<AssertionError> iter = errors.listIterator(errors.size()); while (iter.hasPrevious()) { AssertionError err = iter.previous(); err.printStackTrace(); if(iter.previousIndex() == -1){ throw err; } } } }
Here is a thread that can be called multiple times. Override the test () method.
package mTTest; import static org.junit.Assert.assertEquals; public class MyTestThread extends Thread { UUT dut; public MyTestThread(UUT dut) { this.dut =dut; } @Override public final void run() { try{ test(); } catch (AssertionError ex){ DUTTest.handle(ex); } } void test(){ assertEquals("set-get", "This will cause an ERROR", dut.pop()); assertEquals("set-get", "hello", dut.pop()); } }
source share