Search code examples
c#vs-unit-testing-framework

UnitTesting : COM object that has been separated from its underlying RCW cannot be used


I Have created one UnitTesting Project in C# and facing some issues.

Firstly, I wanted to do some Connect functionality that should happen only once in the beginning. After that i am trying to read some records from Excel file and testing some insert operations and each time insert happens TestCleanUp() gets fired after that constructor gets called then Initialize method. I dont want constructor to get fire after each record is inserted only once. I am confused where to put my Connect functionality and how to avoid calling constructor every time.

[TestClass]
    public class TestConnection
    {
        private TestContext testContextInstance;
        private static iCAM70003SDKC o_DeviceControl = null;

        /// <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;
            }
        }



        [ClassInitialize()]   
        public static void Initialize()
        {

            int iResult = 0;
            EOperationalMode OperationalMode;



        }

Now i am able to make a initial connection in ClassInitialize as suggested. Now as i am creating instance of my COM object in ClassInitialize now making initial connection. Now i have different Testmethod to be tested . Now when i run my program i get Exception after executing first testmethod "COM object that has been separated from its underlying RCW cannot be used”?

I guess when it is trying to execute second testmethod COM object is getting destroyed. How to keep this COM object alive ? I am not calling ReleaseCOMObject.


Solution

  • You can make a static method decorated with [ClassInitalize] which will only run once for the test class. This is a great place to establish an initial connection.