bsg
bsg

Reputation: 253

NUnit error at index -1

I'm attempting to NUnit test adding an element to a collection from a new thread. This is the test function I'm using:

[Test]
public void WorkerThreadAccess()
{
    string foo = "Foo";
    Collection<string> collection = new Collection<string>();
    System.Threading.Thread thread = 
              new System.Threading.Thread(() => collection.Add(foo));
    thread.Start();

    Collection<string> expected = new Collection<string> { foo };
    System.Threading.Thread.Sleep(0);
    CollectionAssert.AreEqual(expected, collection);
}

When I run the test once, it passes. However on every subsequent test without closing NUnit GUI, NUnit fails the Assert with a weird error:

Expected and actual are both <System.Collections.ObjectModel.Collection1[System.String]`> with 1 elements
Values differ at index [0]
String lengths are both 3. Strings differ at index -1.
Expected: "Foo"
But was: "Foo"

Can anyone give some insight to what is going wrong? The elements look the same to me, and index -1 should only be returned on an IndexOf() error.

EDIT: I'm using NUnit 2.5.7

Upvotes: 0

Views: 1095

Answers (1)

Ilia G
Ilia G

Reputation: 10221

try replacing System.Threading.Thread.Sleep(0); with thread.Join();

What you actually want is to wait for the second thread to complete, not just pause the current one.

Upvotes: 1

Related Questions