Вот облегченное решение:
Вот класс, который вы хотите протестировать:
package mTTest;
/**
* UUT class is the Unit Under Test. This will be tested.
* It has two simple method:
* push(): sets the message string if it's null, and waits otherwise.
* pop(): if there is any message sets it null and returns it.
*
*/
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;
}
}
Вот тестовый класс. Это будет вызвано средой JUnit. Перепишите метод multiTest ().
пакет mTTest;
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;
/**
* This is the JUnit test class. Method in this class will invoked by the JUnit
* framework.
*/
public class DUTTest {
/**
* Stores sub test threads errors.
*/
private static List<AssertionError> errors;
/**
* sub test threads call this function with they errors.
* @param err
*/
static void handle(AssertionError err){
errors.add(err);
}
/**
* Simpler single thread test
* @throws InterruptedException
*/
@Test
public void testSingle() {
UUT dut = new UUT();
dut.push("hello");
assertEquals("set-get", "hello", dut.message);
}
/**
* Complex multi-thread test
* @throws InterruptedException
*/
@Test
public void testMulti() throws Exception {
/*
* Initialization
*/
errors = Collections.synchronizedList(new ArrayList<AssertionError>());
UUT dut = new UUT();
MyTestThread th = new MyTestThread(dut);
/*
* Tests
*/
dut.push("hello");
assertEquals("set-get", "hello", dut.message);
th.start();
dut.push("hello");
th.join();
/*
* Error handling
*/
ListIterator<AssertionError> iter = errors.listIterator(errors.size());
while (iter.hasPrevious()) {
AssertionError err = iter.previous();
err.printStackTrace();
if(iter.previousIndex() == -1){
throw err;
}
}
}
}
Вот тема, которую можно вызывать несколько раз. Переопределить метод test ().
package mTTest;
import static org.junit.Assert.assertEquals;
/**
* This is the custom test thread class. The main test thread (which is started
* by JUnit) starts this thread.
*
*/
public class MyTestThread extends Thread {
UUT dut;
/**
* Constructor
* @param dut : should be overwritten to your custom DUT-class
*/
public MyTestThread(UUT dut) {
this.dut =dut;
}
/**
* run() method is final to prevent overriding. Override test instead.
* It just calls the test method and handle the assertion errors.
*/
@Override
public final void run() {
try{
test();
} catch (AssertionError ex){
DUTTest.handle(ex);
}
}
/**
* Write your tests here. run calls this function.
*/
void test(){
assertEquals("set-get", "This will cause an ERROR", dut.pop());
assertEquals("set-get", "hello", dut.pop());
}
}