title: Test helper for expected events sequence reporting duplicate events
body: <p>I have a helper method for my unit tests that asserts that a specific sequence of events were raised in a specific order. The code is as follows:</p>
  
  <pre><code>public static void ExpectEventSequence(Queue&lt;Action&lt;EventHandler&gt;&gt; subscribeActions, Action triggerAction)
  {
      var expectedSequence = new Queue&lt;int&gt;();
      for (int i = 0; i &lt; subscribeActions.Count; i++)
      {
          expectedSequence.Enqueue(i);
      }
  
      ExpectEventSequence(subscribeActions, triggerAction, expectedSequence);
  }
  
      public static void ExpectEventSequence(Queue&lt;Action&lt;EventHandler&gt;&gt; subscribeActions, Action triggerAction, Queue&lt;int&gt; expectedSequence)
      {
          var fired = new Queue&lt;int&gt;();
          var actionsCount = subscribeActions.Count;
  
          for(var i =0; i&lt; actionsCount;i++)
          {
              subscription((o, e) =&gt;
                  {
                      fired.Enqueue(i);
                  });
          }
  
          triggerAction();
  
          var executionIndex = 0;
  
          var inOrder = true;
  
          foreach (var firedIndex in fired)
          {
  
              if (firedIndex != expectedSequence.Dequeue())
              {
                  inOrder = false;
                  break;
              }
  
              executionIndex++;
          }
  
          if (subscribeActions.Count != fired.Count)
          {
              Assert.Fail("Not all events were fired.");
          }
  
          if (!inOrder)
          {
              Assert.Fail(string.Format(
                  CultureInfo.CurrentCulture,
                  "Events were not fired in the expected sequence from element {0}",
                  executionIndex));
          }
  
      }
  </code></pre>
  
  <p>Example usage is as follows:</p>
  
  <pre><code>    [Test()]
      public void FillFuel_Test([Values(1, 5, 10, 100)]float maxFuel)
      {
          var fuelTank = new FuelTank()
          {
              MaxFuel = maxFuel
          };
  
          var eventHandlerSequence = new Queue&lt;Action&lt;EventHandler&gt;&gt;();
  
          eventHandlerSequence.Enqueue(x =&gt; fuelTank.FuelFull += x);
  
          //Dealing with a subclass of EventHandler
          eventHandlerSequence.Enqueue(x =&gt; fuelTank.FuelChanged += (o, e) =&gt; x(o, e));
  
          Test.ExpectEventSequence(eventHandlerSequence, () =&gt; fuelTank.FillFuel());
      }
  </code></pre>
  
  <p>And the code under test:</p>
  
  <pre><code>    public float Fuel
      {
          get
          {
              return fuel;
          }
          private set
          {
              var adjustedFuel = Math.Max(0, Math.Min(value, MaxFuel));
  
              if (fuel != adjustedFuel)
              {
                  var oldFuel = fuel;
  
                  fuel = adjustedFuel;
  
                  RaiseCheckFuelChangedEvents(oldFuel);
              }
          }
      }
  
      public void FillFuel()
      {
          Fuel = MaxFuel;
      }
  
      private void RaiseCheckFuelChangedEvents(float oldFuel)
      {
          FuelChanged.FireEvent(this, new FuelEventArgs(oldFuel, Fuel));
  
          if (fuel == 0)
          {
              FuelEmpty.FireEvent(this, EventArgs.Empty);
          }
          else if (fuel == MaxFuel)
          {
              FuelFull.FireEvent(this, EventArgs.Empty);
          }
  
          if (oldFuel == 0 &amp;&amp; Fuel != 0)
          {
              FuelNoLongerEmpty.FireEvent(this, EventArgs.Empty);
          }
          else if (oldFuel == MaxFuel &amp;&amp; Fuel != MaxFuel)
          {
              FuelNoLongerFull.FireEvent(this, EventArgs.Empty);
          }
      }
  </code></pre>
  
  <p>So the test expects <code>FuelFilled</code> to be fired before <code>FuelChanged</code> but in actuality <code>FuelChanged</code> is fired first, which fails the test.</p>
  
  <p>However my test is instead reporting that <code>FuelChanged</code> is being fired twice, but when I step through the code it is clear that <code>FuelFilled</code> is fired after <code>FuelChanged</code> and <code>FuelChanged</code> is only fired once.</p>
  
  <p>I assumed that it was something to do with the way lambdas work with local state, maybe the for loop iterator variable was only ever set to the final value, so I replaced the for loop with this:</p>
  
  <pre><code>        var subscriptions = subscribeActions.ToList();
  
          foreach (var subscription in subscriptions)
          {
              subscription((o, e) =&gt;
                  {
                      var index = subscriptions.IndexOf(subscription);
                      fired.Enqueue(index);
                  });
          }
  </code></pre>
  
  <p>However the result is the same, fired contains {1;1} instead of {1;0}.</p>
  
  <p>Now I'm wondering if the same lambda is being assigned to both events instead of using the different subscription / index state. Any ideas?</p>
  
  <p><strong>Update:</strong> I was unable to get success with either answer posted so far (same as my initial results), despite their similarities to my actual code, so I presume the issue is located elsewhere in my <code>FuelTank</code> code. I've pasted the full code for <code>FuelTank</code> below:</p>
  
  <pre><code>public class FuelTank
  {
      public FuelTank()
      {
  
      }
  
      public FuelTank(float initialFuel, float maxFuel)
      {
          MaxFuel = maxFuel;
          Fuel = initialFuel;
      }
  
      public float Fuel
      {
          get
          {
              return fuel;
          }
          private set
          {
              var adjustedFuel = Math.Max(0, Math.Min(value, MaxFuel));
  
              if (fuel != adjustedFuel)
              {
                  var oldFuel = fuel;
  
                  fuel = adjustedFuel;
  
                  RaiseCheckFuelChangedEvents(oldFuel);
              }
          }
      }
  
      private float maxFuel;
  
      public float MaxFuel
      {
          get
          {
              return maxFuel;
          }
          set
          {
              if (value &lt; 0)
              {
                  throw new ArgumentOutOfRangeException("MaxFuel", value, "Argument must be not be less than 0.");
              }
              maxFuel = value;
          }
      }
  
      private float fuel;
  
      public event EventHandler&lt;FuelEventArgs&gt; FuelChanged;
  
      public event EventHandler FuelEmpty;
  
      public event EventHandler FuelFull;
  
      public event EventHandler FuelNoLongerEmpty;
  
      public event EventHandler FuelNoLongerFull;
  
      public void AddFuel(float fuel)
      {
          Fuel += fuel;
      }
  
      public void ClearFuel()
      {
          Fuel = 0;
      }
  
      public void DrainFuel(float fuel)
      {
          Fuel -= fuel;
      }
  
      public void FillFuel()
      {
          Fuel = MaxFuel;
      }
  
      private void RaiseCheckFuelChangedEvents(float oldFuel)
      {
          FuelChanged.FireEvent(this, new FuelEventArgs(oldFuel, Fuel));
  
          if (fuel == 0)
          {
              FuelEmpty.FireEvent(this, EventArgs.Empty);
          }
          else if (fuel == MaxFuel)
          {
              FuelFull.FireEvent(this, EventArgs.Empty);
          }
  
          if (oldFuel == 0 &amp;&amp; Fuel != 0)
          {
              FuelNoLongerEmpty.FireEvent(this, EventArgs.Empty);
          }
          else if (oldFuel == MaxFuel &amp;&amp; Fuel != MaxFuel)
          {
              FuelNoLongerFull.FireEvent(this, EventArgs.Empty);
          }
      }
  }
  </code></pre>
  
  <p><code>FuelEventArgs</code> looks like this:</p>
  
  <pre><code>public class FuelEventArgs : EventArgs
  {
      public float NewFuel
      {
          get;
          private set;
      }
  
      public float OldFuel
      {
          get;
          private set;
      }
  
      public FuelEventArgs(float oldFuel, float newFuel)
      {
          this.OldFuel = oldFuel;
          this.NewFuel = newFuel;
      }
  }
  </code></pre>
  
  <p>The <code>FireEvent</code> extension method is looks like this:</p>
  
  <pre><code>public static class EventHandlerExtensions
  {
      /// &lt;summary&gt;
      /// Fires the event. This method is thread safe.
      /// &lt;/summary&gt;
      /// &lt;param name="handler"&gt; The handler. &lt;/param&gt;
      /// &lt;param name="sender"&gt;  Source of the event. &lt;/param&gt;
      /// &lt;param name="args"&gt;    The &lt;see cref="EventArgs"/&gt; instance containing the event data. &lt;/param&gt;
      public static void FireEvent(this EventHandler handler, object sender, EventArgs args)
      {
          var handlerCopy = handler;
  
          if (handlerCopy != null)
          {
              handlerCopy(sender, args);
          }
      }
  
      /// &lt;summary&gt;
      /// Fires the event. This method is thread safe.
      /// &lt;/summary&gt;
      /// &lt;typeparam name="T"&gt; The type of event args this handler has. &lt;/typeparam&gt;
      /// &lt;param name="handler"&gt; The handler. &lt;/param&gt;
      /// &lt;param name="sender"&gt; Source of the event. &lt;/param&gt;
      /// &lt;param name="args"&gt; The &lt;see cref="EventArgs"/&gt; instance containing the event data. &lt;/param&gt;
      public static void FireEvent&lt;T&gt;(this EventHandler&lt;T&gt; handler, object sender, T args) where T : EventArgs
      {
          var handlerCopy = handler;
  
          if (handlerCopy != null)
          {
              handlerCopy(sender, args);
          }
      }
  }
  </code></pre>
  
  <p>The full test code can be found above in the question, there is no other code called during test execution.</p>
  
  <p>I am using NUnit test framework via the Unity Testing Tools plugin for the Unity3D engine, .NET version 3.5 (ish, it's closer to Mono 2.0, I believe), and Visual Studio 2013.</p>
  
  <p><strong>Update 2:</strong></p>
  
  <p>After extracting the code and tests to their own project (outside of the Unity3D ecosystem) all tests run as expected, so I'm going to have to chalk this one up to a bug in the Unity -> Visual Studio bridge.</p>