Mocking and Marshal.ReleaseComObject ()

I have a problem with layout settings, so I can call Marshal.ReleaseComObject()Mocked on my object.

I use Moq to customize the layout of the IFeature type (from a third-party interface library). The breadboard installation is quite simple:

  var featureMock = new Mock<IFeature>(); 
  IFeature feature = featureMock.Object; 

In my code, an object object is created in a while loop, passing through the cursor ( FeatureCursor) type. Due to outdated third-party library problems, the object Featuredetected memory leak problems. Thus, I have to free objects through Marshal.ReleaseComObject(), as shown in the code;

public class XXX
{

      public void DoThis()
      {
        IFeatureCursor featureCursor; 
        //...fill the cursor with features; 

        IFeature feature = null; 
        while ((feature = featureCursor.NextFeature)!= null)
        {
           //Do my stuff with the feature
          Marshal.ReleaseComObject(feature); 
        }

      }

}

It works when I use a real sign and functions, but when I mock a function in unittest, I get an error message:

"System.ArgumentException : The object type must be __ComObject or derived from __ComObject."

But how to apply this to my mock object?

+4
1

Mocked IFeature .NET-, COM, The object type must be __ComObject....

Marshal.ReleaseComObject(feature); , COM :

if (Marshal.IsComObject(feature)
{
    Marshal.ReleaseComObject(feature);
}

, Marshal.ReleaseComObject ( ).

, - , Marshal.ReleaseComObject , .

, , , :

public interface IMarshal
{
    void ReleaseComObject(object obj);
}

public class MarshalWrapper : IMarshal
{
    public void ReleaseComObject(object obj)
    {
        if (Marshal.IsComObject(obj))
        {
            Marshal.ReleaseComObject(obj);
        }
    }
}

IMarshal, :

public void FeaturesAreReleasedCorrectly()
{
    var mockFeature = new Mock<IFeature>();
    var mockMarshal = new Mock<IMarshal>();

    // code which calls IFeature and IMarshal
    var thing = new Thing(mockFeature.Object, mockMarshal.Object);
    thing.DoThis();

    // Verify that the correct number of features were released
    mockMarshal.Verify(x => x.ReleaseComObject(It.IsAny<IFeature>()), Times.Exactly(5));
}
+5

Source: https://habr.com/ru/post/1526529/


All Articles