Freigeben über


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

Let's say you're writing unit tests for code which uses COM objects. You want some initialization and some cleanup to be done. So you set up your test:

 private static MyStore store;

 [ClassInitialize()]
public static void MyClassInitialize(TestContext testContext)
{
    store = new MyStore("some value");
}

 [ClassCleanup]
public static void MyClassCleanup()
{
    store.DoWork(someArgument);
}

However, as your 'store' instance uses a COM object, you will get a test run error, saying: "System.Runtime.InteropServices.InvalidComObjectException: COM object that has been separated from its underlying RCW cannot be used..".

The way to solve this issue is to open up your testrunconfig file using the XML editor and adding the highlighted element to it:

 <?xml version="1.0" encoding="UTF-8"?>
<TestRunConfiguration name="Local Test Run" id="fbbfe81f-97fa-4e33-bde1-00b3827b933e" xmlns="https://microsoft.com/schemas/VisualStudio/TeamTest/2006">
   < ExecutionThread apartmentState="MTA"   /> 
  <Description>This is a default test run configuration for a local test run.</Description>
  <TestTypeSpecific />
</TestRunConfiguration>

The ExecutionThread element will instruct the test to use the MTA threading model. This way, the static instance of "store" can be shared across tests.

Comments

  • Anonymous
    March 26, 2010
    Thanks, this solved my case.

  • Anonymous
    January 14, 2011
    If you use Visual Studio, you must restart it to take the settings into effect.