0

I need to write junit tests for a method that implements the runnable and the whole logic of the code is within run() method. for example:

public  class BookmarkController{
 public void addBookmark(final String url, final String title) {
       Runnable r = new Runnable() {
                   @Override
                   public void run() {
                                     //some logic

                                    };
}
}

can anybody tell me how to write tests for the method.

2 Answers2

0

You run addBookmark() then I'm assuming you have a getBookmarks() method. After you run the addBookmark()method, you check the getBookmarks() method to see if the bookmark you added with addBookmark() has been added. If the thread that implements Runnable is expected to take some time, you do the test in a RetriedAssert which will retry the test over and over for a certain length of time. Effectively waiting a certain length of time for a pass, if it still finds fails after the length of time, it's a fail.

new RetriedAssert(2000,100){
  public void run() throws Exception{
    assertTrue(yourClass.getBookMarks().contains(bookmark));
  }
}.start();
Ross Drew
  • 8,163
  • 2
  • 41
  • 53
0

In general , anonymous classes is equivalent to private methods, ie: implementation details are private, and ideally you should test the behaviour. It should be sufficient enough if your test check if BookMark is added. Also you can think of using Mock framework (Setting expectations/ Verifying )

Satheesh Cheveri
  • 3,621
  • 3
  • 27
  • 46