title: Testing an async method call
body: <p>Below is a simplified setup of my application. It has a class Foobar which calls on a facade method for fetching data. The facade then calls on a web service to actually get the data and then manipulates the data a bit and then returns it to Foobar.</p>
  
  <p>Now because the web service might take a good while to run, the method call to the facade needs to be asynchronous. Hence the facade's method doesn't have a return value, but instead, the method uses a callback object. Look at the example and continue reading below.</p>
  
  <pre><code>public class Foobar {
      private List&lt;DTO&gt; dtos;
  
      @Autowired
      private Facade facade;
  
      public void refresh() {
          facade.refreshFoobar(new CallBack() {
              public void dataFetched(List&lt;DTO&gt; dtos) {
                  setDtos(dtos);
              }
  
          });
      }    
  
      public void setDtos(List&lt;DTO&gt; dtos) {
          this.dtos = dtos;
      }
  }
  
  
  public class Facade {
  
      ...
  
      public void refreshFoorbar(CallBack cb) {
          // Fetch data from a web service
          List&lt;DTO&gt; dtos = webService.getData();  
          // Manipulate DTOs
          ....
          // call on the callback method
          cb.dataFecthed(dtos);
      }
  
  }
  </code></pre>
  
  <p>I have two ways of making the facade's method asynchronous, either by creating a thread manually or by using springs @Async annotation.</p>
  
  <pre><code>public class Facade {
  
      public void refreshFoorbar(CallBack cb) {
          new Thread() {
  
              @Override
              public void run() {
                  ....
              }
  
          }.start();
  
      }
  }
  
  // ... OR ...
  
  public class Facade {
  
      @Async
      public void refreshFoorbar(CallBack cb) {
          ....    
      }
  }
  </code></pre>
  
  <p>My problem is that I now need to write an integration test for this chain of method calls. I think I need to force the async facade call to be synchronous when the integration test is ran, otherwise I won't know for sure when I can do the appropriate asserts. The only idea for making the method call synchronous is to use manually handled threads AND making the threading conditional (so, for testing purposes, I have an if clause which determines if the facade method should be ran in a separate thread or not).</p>
  
  <p>However, I have a feeling that there could be a better solution to my problem, whether it be a better way of forcing the method to me synchronous, eg with spring, or by testing the multithreading on some way. </p>
  
  <p>This is where I need your suggestions, how would you solve my problem? Note, I'm using junit for both unit and integration tests.</p>