简体   繁体   中英

MSTest unit test passes when in “debug” mode, but fails final assertion in “run” mode

Hi I have a unit test that goes attaches to an event and updates a counter based on a property of the eventArgs in the handler like so:

protected void UpdateCounts(object sender, EventArgs eventArgs)
{
  lock (lockobject)
  {
    Counts[eventArgs.Target]++;
  }
}

Counts is a static Dictionary resource that all unit tests in that class share. I assert that at the end of the test I assert the count to be 6 for a certain value of Target (Target is an enum). When I debug through this test, it always passes that final assertion, however, when I just run it without any breakpoints, the count for that value of Target can be 7 or 8, but never 6.

I realize that many threads trying to access an entry in a Dictionary may present a race condition, which is why I placed the lock around the increment. I also have a TestInitialize method which runs before every test gets run that looks like this:

[TestInitialize]
public void InitTest()
{
  foreach (TargetType x in Enum.GetValues(typeof(Target)))
  {
    Counts[x] = 0;
  }
}

Does anybody have any insight as to what is going on here?

Almost every time I have run into this issue it boils down to a race condition which is less likely to occur when you are debugging since you are slowing the execution down as you step through the code.

I would suggest adding debug or trace statements into the threads as they reach various stages of execution in order to identify where the race condition exists.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM