开发者

Losing field of delegated value

I'm trying to understand whats happening here. I'm writing some unit tests for asynch'd remoting code

    // a global variable to all unit tests in the class
    private List<ModuleInfo> _moduleInfo;

    [TestMethod]
    public void MyFunction()
    {
           _moduleInfo = new List<ModuleInfo>();

            netCall.MessageRecieved +=
                    delegate(object sende开发者_JAVA百科r, MessageTestRecievedEventArgs e)
                    {
                       // I get a correct response - array of Modules
                       // then try to add to global variable
                       foreach (EducateMe.Shared.Types.ModuleInfo mIn in arr)
                       {
                           _moduleInfo.Add(mIn);
                       }
                    }

    }

// so after the loop the variable _moduleInfo count = 9 // next Test that runs however the variable is empty - so when it leaves the closure it gets reset somehow - how might I preserve this value between tests?

Update -

This is how the array is defined. There's no [Setup] or [TearDown] being used.

[TestClass]
public class MyUnitTest
{
  private List<ModuleInfo> _moduleInfo;

  // then the function definition

}

There is a second unit test that is simply an attempt to read the value created by the loop. So MyFunction() test passes fine, but once it exits the closure the variable is gone.

Cheers

PS. This has come with the VS-created unit test

    private TestContext testContextInstance;

    /// <summary>
    ///Gets or sets the test context which provides
    ///information about and functionality for the current test run.
    ///</summary>
    public TestContext TestContext
    {
        get
        {
            return testContextInstance;
        }
        set
        {
            testContextInstance = value;
        }
    }


Are you sure it's not just creating a new instance of your test class for each test? That seems pretty reasonable behaviour to me - one test shouldn't rely on other tests having executed. It looks like you should be using [SetUp] instead.


Don't know which Testing Framework you are using but in in NUnit there are methods, that can have the attribute [Setup] and [TearDown]. Maybe one of these functions resets the list?

Nevertheless this is a very bad design for unit tests. By this way you design a coupling between two test. So you can never run the second test without running the first test and how do you ensure in which order tests are run?

So instead write some utility function that fills up _moduleInfo within each test with some stubs that are containing the expected values.

A very good source about how to do testing is the book The Art of Unit Testing: With Examples in .Net.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜