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
Let's say I have the following simple setup:

public void MethodTested()
    MyObject obj = new MyObject();

Is it possible to mock the constructor invocation and call some custom code at the time of MyObject instantiation? Something along these lines:

Isolate.WhenCalled( () => new MyObject() ).DoInstead( context =>
    // Do something 
} );
asked by roman (2.2k points)

3 Answers

0 votes
Hello Roman,

You can fake the constructor so it will not be executed, however you can't specify custom code to run instead.

You can use something like:

var fakeMyObject = Isolate.Fake.Instance<MyObject>(Members.CallOriginal, ConstructorWillBe.Ignored);

to create an instance of MyObject that will have all its methods call their original implementations, but the constructor will not be executed. Then you can fake a particular method and replace its logic with DoInstead.

Hope that helps.
answered by igal (5.7k points)
0 votes
Bummer... it would definitely be useful to specify a delegate to be executed when a constructor runs. Would be preferable to do it in a strongly-typed manner, though the following might work as well - Isolate.NonPublic.WhenCalled(obj, "MyObject") or Isolate.NonPublic.WhenCalled(obj, ".ctor").

The scenario I'm trying to set up is verifying that method calls occur within a transaction, i.e. set up a list of Actions and make sure that they haven't been called at the time that a TransactionScope object is instantiated and have been called at the time of TransactionScope.Complete().

I was able to get around this, because we have a custom container around TransactionScope, which happens to call a private _initialize method in the constructor and I could set up the DoInstead logic around _initialize. This is of course not ideal, as it exposes implementation.
answered by roman (2.2k points)
0 votes
Hi Roman,

There a workaround to this case using Isolator natural API (previous generation of the API). You can register to a type constructors calls with callback.

For example:
public void CallBackOnCtorCalls()
    var mock = MockManager.MockAll<MyClass>();
    bool wasCalled = false;
    mock.MethodSettings(".ctor").MockMethodCalled += (sender, args) => wasCalled = true;


    new MyClass();


This code will notify when a class of MyClass type is initialized.

Please let us know if it helps to test the case you presented.

Typemock Support
answered by Elisha (12k points)