2

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?

user1168608
  • 598
  • 2
  • 10
  • 27
  • 1
    the execution of TestMethods is not deterministic, so have no control of the order. TestInitialize or setup-help methods is the way forward. They will also execute i parallell so independent test is the most stable and easiest way as well – Jocke May 22 '17 at 08:30
  • @Jocke Actually we had an idea of automating all the test methods, by naming the Test methods in ascending order, so that they would run in that order. So is this not possible? – user1168608 May 22 '17 at 09:26
  • @user1168608 Whether it's possible is an implementation detail of the unit-test runner. Regardless, it's a really bad idea - unit-tests should be completely independent of each other for lots of reasons - better performance (they can be parallelized), better maintainability, etc. – RB. May 22 '17 at 09:42

1 Answers1

4

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);
        }
    }
}
Community
  • 1
  • 1
RB.
  • 36,301
  • 12
  • 91
  • 131