user1168608 user1168608 -4 years ago 71
C# Question

Passing information from one [TestMethod] to other in C# unit test framework

I would like create an object in one Test method and use the created object in rest of the other [TestMethod]'s rather than re-writing the code to create. I was trying to declare a global variable inside the class and assign it during the creation test method. But when the control goes to next [TestMthod] the value of global variable becomes null.

namespace ABC
{
class UnitTest
{
[TestMethod]
public void CreateObject()
{
var createdObject = \\ logic to create object;
}

[TestMethod]
public void Display()
{
//Here i want to use the created object instead of using object.
}
}
}


How do i achieve this?

Answer Source

Unit-tests should be completely atomic - someone might want to run the Display unit-test on it's own, or they might get run in parallel, or a different order to what you require. What you actually want to do is to mark your CreateObject method with the [TestInitialize] method. Note that CreateObject is NOT a unit-test method - it's a test setup method, as it should be.

For reference, the full list of test setup attributes is described here - you could also use ClassInitialize depending on the specifics of how you want to create your object.

namespace ABC
{
    class UnitTest
    {
        private object mySpecialObject;

        [TestInitialize]
        public void CreateObject()
        {
            mySpecialObject = CreateSpecialObject();
        }

        [TestMethod]
        public void Display()
        {
            //Here i want to use the created object instead of using object.
            DoStuff(mySpecialObject);
        }
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download