Question

I have always got around this problem by - unfortunately - using events less. However this time I came up with a nifty trick, however I don't think the following would be considered a proper approach. Is there a recommended method to achieve the same results?

NB Without the while you get a null reference exception on the _args.Fixture unless you breakpoint on it - race condition.

private Parser _parser;
private ParsedArgs _args;        

[TestFixtureSetUp]
public void Setup()
{
    _parser = new Parser();
    _parser.DataParsed += DataParsed;
}

void DataParsed(object sender, ParsedArgs e)
{
    _args = e;
}

[Test]
public void TestDocParse()
{
    _parser.ParseFixture(File.ReadAllText(EventDataPath));

    while (_args == null || _args.Fixture == null) { }

    Assert.IsNotNull(_args.Fixture);
    var fixture = _args.Fixture;
    Assert.AreEqual("2F7PY1662477", fixture.Id);            
}

I found that the following led to having to think up a potentially inaccurate timescale for the parsing to have completed...

I am aiming to test that the fixture.Id is equal to "2F7PY1662477".

Thanks

Was it helpful?

Solution

I would first decouple the test/fixture from requiring some sort of file to read. I would just send in canned data to ParseFixture--you're either testing that you can parse a file or you're testing whether the expected event is raised.

I would then avoid parsing in the background. This will illuminate the race condition because you'll do everything synchronously.

I would then have a flag that signals whether a valid event occurred.

For example:

private bool eventOccurred;
private void DataParsed(object sender, ParsedArgs e)
{
   eventOccurred = e.Id == "2F7PY1662477";
}

[Test]
public void TestDocParse()
{
    _parser.ParseFixture(TextToParse);
    Assert.IsTrue(eventOccurred);
}

OTHER TIPS

System.Threading.SpinWait.SpinUntil
    (() => _args != null && _args.Fixture != null, 30000);

This makes sure that the parser has completed its job, however it won't leave my tests running if there has been an issue somewhere.

Thanks vcsjones

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top