0

I want to instantiate an object only once per assembly. How can I pass an object to the AssemblyInit Method?

I'm getting a compilation error. An object reference is required for the non-static field, method or property testcounter.

namespace Tests
{    
    [TestClass]
    public class Counters
    {   
        int testcounter = 0;
             
        [AssemblyInitialize]
        public static void AssemblyInit(TestContext context)
        {
           testcounter = 1;
        }
    
        [TestMethod]
        public void testcounter()
        {
           Assert.AreEqual(testcounter,1);
        }
    }
}
Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
agent_bean
  • 1,493
  • 1
  • 16
  • 30
  • Your error is because `testcounter` is not a static field; the error doesn't have anything directly to do with `AssemblyInit`'s parameter. – Joe Sewell Sep 28 '20 at 15:28
  • i need to initialize some classes which aren't static inside the AssemblyInit. so is this possible? – agent_bean Sep 28 '20 at 15:38
  • No, that is not possible (at least not without trying to circumvent the intended usage of those hooks). Use TestInitialize or ClassInitialize, depending on your specific needs. Mind you that you may prevent (successfull) parallel execution of your tests if you get that wrong. You might consider asking a more specific/detailed question if you need more information. In case of doubt initialize your classes inside each test. – Christian.K Sep 28 '20 at 15:40
  • [Related](https://stackoverflow.com/q/1873191/21567). – Christian.K Sep 28 '20 at 15:41
  • I get the same problem for ClassInitialize. TestInitialize works but it runs every test, which is what i'm trying to avoid, because initialization for each test takes around 30 seconds to 1 minute. – agent_bean Sep 28 '20 at 16:14

0 Answers0