简体   繁体   中英

create junit test for runnable class

I have a runnable class as shown below,

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);
  }
}

I want to create Junit test cases for this runnable. As I am new to write Junit test cases , please let me know what is the best approach for this. I Created Junit test as shown below,

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());
  }
}

Please help me and let me know is this correct approach

To test the runnable running in a separate thread, the JUnit test should (1) construct the runnable, (2) start a thread constructed on the runnable, (3) queue a few entries, (4) wait for a short period, (5) call stop(), and (6) check that all entries got processed.

In this case, your code will fail the test since your run() method does not have a loop and thus will only process the first entry. It also doesn't have any code for processing the entry and doesn't compile yet.

In addition to the JUnit test, you need to do a careful code inspection for concurrency issues. For example, processEntries needs to be volatile.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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