我有一个在线程中运行的进程(用作实时信号分析进程)。我想给这个线程进程提供已知输入,然后在jUnit中测试,以确保输出正确。我有一个回调监听器,当线程完成处理数据时可以通知我,我可以通过将测试用例本身注册为侦听器,在结果上成功运行断言。
当这些断言失败时,它们会抛出异常。但是由于它们发生在测试方法之外,jUnit没有将此异常注册为失败。
我该如何结构化我的jUnit测试,以便在侦听器返回后正确地失败测试?以下是代码的简化版本。
public class PitchDetectionTest extends TestCase
implements EngineRunCompleteListener() {
AudioData fixtureData;
PitchDetectionEngine pitchEngine;
public void setUp() {
fixtureData = <stuff to load audio data>;
}
public void testCorrectPitch() {
pitchEngine = new PitchEngine(fixtureData);
pitchEngine.setCompletionListener(this);
pitchEngine.start();
// delay termination long enough for the engine to complete
try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); }
}
// gets called by the PitchEngine when it has finished processing all data in the
// fixtureData. This is the only method defined by interface
// EngineRunCompleteListener.
public void notifyEngineRunComplete() {
// The real code asserts things about the PitchEngine's results. When they fail,
// an exception is thrown that I can see in the console, but this unit test still
// shows as 'success' in the jUnit interface. What I want is to see
// testCorrectPitch() fail.
assertTrue(false);
}
}
public class PitchEngine () {
EngineRunCompleteListener completionListener();
Thread myThread;
public void start() {
// other stuff
myThread = new Thread(this);
myThread.start();
}
public void run() {
while (some condition) {
// do stuff with the data
}
if (engineRunCompleteListener != null) {
engineRunCompleteListener.notifyEngineRunComplete();
}
}
}