如何jUnit测试另一个线程中的代码结果

Ida*_*oEv 13 java junit multithreading

我有一个在线程中运行的进程(用作实时信号分析过程).我想为该线程进程提供已知输入,然后在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();
    }
  }

}
Run Code Online (Sandbox Code Playgroud)

Yon*_*oni 9

你已经有两个线程在运行.你的junit线程和进程线程( 从头开始myThread.start().
我能想到你至少有两个选项,所有这些选项都涉及将断言移开notifyEngineRunComplete.例如:

  • 您可以使用join等待进程线程完成,然后执行断言(此处为 Javadoc ).
  • 您可以通过等待监视器对象将您的junit线程置于休眠状态,然后在您的回调函数中通知此监视器.这样你就会知道这个过程已经完成了.
  • 您可以使用ExecutorFuture对象.我认为如果它适用于您的类(这里是 Javadoc ),这将是最酷的解决方案.