HenlenLee
HenlenLee

Reputation: 445

Junit for runnable class and Queue

I have a Processor class which implements Runnable.

The first method

Public Processor implements Runnable{

 //"Event" is the name of this queue
 PersistentQueue<Event> persistentQueue = new PersistentQueue<>("Event");

 //add the Event POJO to the persistentQueue
 public void addToQueue(Event, event) {
     persistentQueue.add(event);         
}

The persistentQueue is to store Event POJO

And the run method

public void run() {
      while (true) {
       if (!persistentQueue.isEmpty()) {

        Event peekEvent = persistantQueue.peek();
        sendRequest(peekEvent);
      }
    }
  }

 public void sendRequest(Event, event){

  // do something to send the event
}

For the first addToQueue method I wrote the test

public class ProcessorTest {

   private Event event;
   private Processor m_Processor;

  @Before
  public void setup() throws IOException {
  //the Processor class is a singleton
  m_Processor = Processor.getProcessor();
  event = new Event();
 }

  @Test
  public void test(){
   PersistentQueue<Event> persistentQueue = new PersistentQueue<> 
 ("Event");
    m_Processor.addToQueue(event);
    assertEquals(1, persistentQueue.size());
  }
}

But the queue size is 0 not 1. I dont know what's the problem. And I also have question about how to test the run method?

Upvotes: 1

Views: 207

Answers (1)

Jacob G.
Jacob G.

Reputation: 29700

In your test method, you created a new queue that has nothing to do with your m_Processor instance; it goes unused entirely. You need to change your code so you can get the PersistentQueue instance contained inside your m_Processor instance. Assuming you have a getter method called getPersistentQueue inside Processor, then you can use the following:

@Test
public void test() {
    m_Processor.addToQueue(event);
    assertEquals(1, m_Processor.getPersistentQueue().size());
}

Upvotes: 1

Related Questions