package edu.hawaii.ics.yucheng;
import junit.framework.TestCase;
/**
* Tests the BackgroundWorker class.
*/
public class BackgroundWorkerTest extends TestCase {
class TestWorker extends BackgroundWorker<String, String> {
boolean error = false;
Exception exception = null;
boolean progress = false;
String result = null;
@Override
protected void processError(final Exception e) {
exception = e;
super.processError(e);
}
@Override
protected void processProgress(final String p) {
result = p;
super.processProgress(p);
}
@Override
protected String run() throws Exception {
if (progress)
sendProgress("Test Progress");
if (error)
throw new Exception("Test Exception");
while (!isCancelled())
Thread.yield();
return "Test Result";
}
}
/**
* Tests the cancel method.
*
* @throws Exception
*/
public void testCancel() throws Exception {
final TestWorker worker = new TestWorker();
worker.start();
Thread.sleep(100);
assertFalse(worker.isCancelled());
worker.cancel();
assertTrue(worker.isCancelled());
worker.cancel();
worker.join();
}
/**
* Tests the isCancelled method.
*
* @throws Exception
*/
public void testIsCancelled() throws Exception {
final TestWorker worker = new TestWorker();
worker.start();
Thread.sleep(100);
assertFalse(worker.isCancelled());
worker.cancel();
assertTrue(worker.isCancelled());
worker.cancel();
worker.join();
}
/**
* Tests the isRunning method.
*
* @throws Exception
*/
public void testIsRunning() throws Exception {
final TestWorker worker = new TestWorker();
assertFalse(worker.isRunning());
worker.start();
Thread.sleep(100);
assertTrue(worker.isRunning());
worker.cancel();
worker.join();
assertFalse(worker.isRunning());
}
/**
* Tests the join method.
*
* @throws Exception
*/
public void testJoin1() throws Exception {
final TestWorker worker = new TestWorker();
worker.join();
}
/**
* Tests the join method.
*
* @throws Exception
*/
public void testJoin2() throws Exception {
final TestWorker worker = new TestWorker();
worker.start();
Thread.sleep(100);
worker.cancel();
worker.join();
}
/**
* Tests the processDelegate method.
*
* @throws Exception
*/
public void testProcessDelegate1() throws Exception {
final TestWorker worker = new TestWorker();
worker.progress = true;
worker.error = true;
worker.start();
Thread.sleep(100);
worker.cancel();
worker.join();
assertEquals("Test Exception", worker.exception.getMessage());
assertEquals("Test Progress", worker.result);
}
/**
* Tests the start method.
*
* @throws Exception
*/
public void testStart1() throws Exception {
final TestWorker worker = new TestWorker();
worker.start();
Thread.sleep(100);
worker.cancel();
worker.join();
}
/**
* Tests the start method.
*
* @throws Exception
*/
public void testStart2() throws Exception {
final TestWorker worker = new TestWorker();
worker.start();
Thread.sleep(100);
try {
worker.start();
fail();
} catch (final IllegalStateException e) {
// This is expected.
}
worker.cancel();
worker.join();
}
}