繁体   English   中英

为可运行类创建junit测试

[英]create junit test for runnable class

我有一个可运行的类,如下所示,

public class WriteToOutputFile implements Runnable{
  BlockingQueue<entry> queue;
  File file;
  volatile boolean processentries;

  WriteToOutputFile(BlockingQueue queue,File file){
    this.queue = queue;
    this.file = file;
    this.processentries= tue;
  }

  @Override 
  public void run(){
    while(processentries && !queue.isEmpty())
      entry = queue.take();

    if (entry== lastentry)break;
      //logic to write entries to file 
  }

  public void stop(){
    processentries = false;
    queue.put(lastentry);
  }
}

我想为这个 runnable 创建 Junit 测试用例。 由于我是编写 Junit 测试用例的新手,请告诉我什么是最好的方法。 我创建了 Junit 测试,如下所示,

testWriteToOutputFile{ 
  @Test  
  functionalitytest(){
    BlockingQueue queue = new BlockingQueue(); 
    File file; 
    WriteToOutputFile workerthread = Powermockito.spy(
      new WriteToOutputFile(queue,file));  
    Thread workerthread = new Thread(workerthread );  
    workerthread.start();  
    queue.put(entry);
    workerthread.stop();  
    assertEquals(0,queue.size());
  }
}

请帮助我,让我知道这是正确的方法

要测试在单独线程中运行的可运行对象,JUnit 测试应该 (1) 构造可运行对象,(2) 启动在可运行对象上构造的线程,(3) 将几个条目排队,(4) 等待一小段时间,( 5) 调用 stop(),和 (6) 检查是否所有条目都得到处理。

在这种情况下,您的代码将无法通过测试,因为您的 run() 方法没有循环,因此只会处理第一个条目。 它也没有任何用于处理条目的代码并且尚未编译。

除了 JUnit 测试之外,您还需要对并发问题进行仔细的代码检查。 例如,processEntries 需要是可变的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM