title: Asynchronous initialization and its unit testing
body: <p><strong>Background</strong>
  I need some class to perform background initialization, which should start in constructor. Currently I'm using a <code>Task</code> which is started by constructor, and then all operations, depending on that initialization wait for that <code>Task</code> completion.</p>
  
  <p>Please take a look at the following simplified example:</p>
  
  <pre><code>interface IEntry {}
  
  interface IRepository
  {
      IQueryable&lt;IEntry&gt; Query { get; }
      void Add(IEntry entry);
  }
  
  class PrefetchedRepository : IRepository
  {
      private readonly Task _prefetchingTask;
      private readonly ICollection&lt;IEntry&gt; _entries = new List&lt;IEntry&gt;();
      private readonly IRepository _underlyingRepository;
  
      public PrefetchedRepository(IRepository underlyingRepository)
      {
          _underlyingRepository = underlyingRepository;
          // Background initialization starts here
          _prefetchingTask = Task.Factory.StartNew(Prefetch);
      }
  
      public IQueryable&lt;IEntry&gt; Query
      { 
          get
          {
              EnsurePrefetchCompleted();
              return _entries.AsQueryable();
          }
      }
  
      public void Add(IEntry entry)
      {
          EnsurePrefetchCompleted();      
          _entries.Add(entry);
          _underlyingRepository.Add(entry);
      }
  
      private void EnsurePrefetchCompleted()
      {
          _prefetchingTask.Wait();
      }
  
      private void Prefetch()
      {
          foreach (var entry in _underlyingRepository.Query)
          {
              _entries.Add(entry);
          }
      }
  }
  </code></pre>
  
  <p>This works. The problem starts when I want to test initialization in Unit Test. I'm creating the instance and providing the mock of underlying repository. I want to ensure that all entries were fetched from the mock as expected.</p>
  
  <pre><code>[TestFixture]
  public class PrefetchingRepositoryTests
  {
      [Test]
      public void WhenInitialized_PrefetchingIsDone()
      {
          // Arrange
          var underlyingRepositoryMock = A.Fake&lt;IRepository&gt;();
  
          // Act
          var target = new PrefetchedRepository(_underlyingRepository);
  
          // Assert
          underlyingRepositoryMock.CallsTo(r =&gt; r.Query).MustHaveHappened(Repeated.Exactly(1));   
      }
  }   
  </code></pre>
  
  <p>As you can imagine, most of the time fails, because actually initialization didn't started yet at the assertion point.</p>
  
  <p><strong>Questions</strong></p>
  
  <p><em>Question 1 - <strong>Initialization</strong>:</em> Is there more elegant way of asynchronous initialization rather than starting task in constructor and waiting for it in all dependent operations?</p>
  
  <p><em>Question 2 - <strong>Testing</strong>:</em> I thought of 2 possible ways to solve race between the test and testee:</p>
  
  <ol>
  <li><p>Using event handle to the test:</p>
  
  <pre><code>[Test]
  public void WhenInitialized_PrefetchingIsDone()
  {
      // Arrange ...
      var invokedEvent = new ManualResetEvent(false);
      underlyingRepositoryMock.CallsTo(r =&gt; r.Query).Invokes(_ =&gt; invokedEvent.Set());
  
      // Act ...
  
      // Assert
      Assert.True(invokedEvent.WaitOne(1000));
  }
  </code></pre></li>
  <li><p>Exposing <code>EnsurePrefetchCompleted</code> method as internal and using it in the Unit Test (assuming usage of <code>[assembly: InternalsVisibleTo("...")]</code>)</p></li>
  </ol>
  
  <p>The problem with both solutions is that in case of failure time duration long (actually in the second case - it is limited by test timeout). </p>
  
  <p>Is there any simpler way to do this kind of testing?</p>