title: Java unit testing - how to unit test an async method (uses callback) with mockito answer
body: <p>I have the following method in the class Logic</p>
  
  <pre><code>public class Logic implements ILogic {
  
  @Override
  public void doSomethingInterestingAsync(final int number, 
                                          final ICallback callback){
      new Thread(new Runnable() {
          @Override
          public void run() {
              callback.response(number+1);
          }
      }).start();
    }
  }
  </code></pre>
  
  <p>and I usually call it using   </p>
  
  <pre><code>ILogic.doSomethingInterestingAsync(1, new ICallback() {
      @Override
      public void response(int number) {
          System.out.println(String.format("response - %s", number));
      }
  });
  </code></pre>
  
  <p>Now I want to unit test it.  </p>
  
  <p>So I figured one solution is with <a href="http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/CountDownLatch.html" rel="nofollow noreferrer">CountDownLatch</a> (found in <a href="https://stackoverflow.com/a/1829949/450602">other</a> SO thread)<br>
  As Follows:  </p>
  
  <pre><code>@Test
  public void testDoSomethingInterestingAsync_CountDownLatch() throws Exception {
      final CountDownLatch lock = new CountDownLatch(1);
  
      ILogic ILogic = new Logic();
      final int testNumber = 1;
      ILogic.doSomethingInterestingAsync(testNumber, new ICallback() {
          @Override
          public void response(int number) {
              assertEquals(testNumber + 1, number);
              lock.countDown();
          }
      });
      assertEquals(true, lock.await(10000, TimeUnit.MILLISECONDS));
  }
  </code></pre>
  
  <p>And it works great.<br>
  But I have also read that about Answer in Mockito might be a better practice for that,<br>
  But I couldn't quite follow the examples.<br>
  How do I write unit tests for methods using call backs using Mockito tools?<br>
  Thanks.  </p>