chevron-thin-right chevron-thin-left brand cancel-circle search youtube-icon google-plus-icon linkedin-icon facebook-icon twitter-icon toolbox download check linkedin phone twitter-old google-plus facebook profile-male chat calendar profile-male
Welcome to Typemock Community! Here you can ask and receive answers from other community members. If you liked or disliked an answer or thread: react with an up- or downvote.
0 votes
I'm mocking a class that has a destrcutor. During some of the test I do not expect my tested code to dispose of the mocked object, and therefore I do not expect the destructor to be called. However, when the object is mocked, TypeMock creates a real .NET instance of the object, which is automatically disposed by the GC after the object gets out of scope.

A call to GC.SuppressFinalize on the object may help, but I was able to do it only when using reflective mocks. With reflective mocks it's very simple: I call GC.SuppressFinalize on the mocked instance that I can get from the MockedInstance property of my mock object.

When using natural mocks, it seems that I do not have access to that instance. I tried calling GC.SuppressFinalize on all the instances received when calling MockManager.GetMockes<MyMockedType>(), but it did not help.

Is there a way to do it, or do I have to give up natural mocks when mocking objects with destructors?
asked by avnerc (600 points)

13 Answers

0 votes
Any idea?
answered by pierre-luc (3.3k points)
0 votes
Hi,

First I apologize for the late reply :oops:

You can use MockManager.GetMockOf<>() method.
It will give you the mock controller, than you can use the the Mock.Object property to get the faked instance.
Note the Mock.Object will be null until you'll create the instance in code under test so you should use it only after new SimpleClass() is called in the test.

Example:
// Assuming this line get called in deep in the tested code.
var sc = new SimpleClass() { Number = 65 };
// Get the mock controller
var mock = MockManager.GetMockOf<SimpleClass>(fakeSimpleClass);
// Get the actual instance.
SimpleClass instance = mock.Object as SimpleClass;
GC.SuppressFinalize(instance);


Hope it helps.
answered by ohad (35.4k points)
0 votes
I got it :-)
I have to use MockManager.GetMocks and not MockManager.GetMockOf

This is the solution/workaround:
            var mocks = MockManager.GetMocks(typeof (DummyClassDisposable));
            foreach (var mock in mocks)
            {
                GC.SuppressFinalize(mock.MockedInstance);
            }


Thanks
answered by pierre-luc (3.3k points)
...