How To Isolate Future Instances

One of the benifits of testing with TypeMock is the ability to mock future objects. Future objects are instances that will be created within the tested code.

 

Here is an example:

private void InitializeComponent() { this.okButton = new System.Windows.Forms.Button(); this.cancelButton = new System.Windows.Forms.Button(); this.ignoreButton = new System.Windows.Forms.Button(); }

We create 3 new Buttons in this method. Suppose we want to isolate the tested code from the Windows.Forms component and mock those buttons.

Here is the easy way:

//Mock all Buttons Mock allButtonsMock = MockManager.MockAll(typeof(Button));

We mock all the Button objects (both future and past). This will mock all our buttons but we won’t be able to set expectations on a specific instance. So if we setup an expecation, the expected method will be mocked for the first instance that calls that specific method.

Here is how to have better control on the instances.

// Mock future instance of Button (okButton) Mock okButtonMock = MockManager.Mock(typeof(Button)); // Mock next instance of Button (cancelButton) Mock cancelButtonMock = MockManager.Mock(typeof(Button)); // Mock future instance of Button (ignoreButton) Mock ignoreButtonMock = MockManager.Mock(typeof(Button));

Now we can control each button seperatly, notice how the SEQUENCE of the Button constructors mathces the ORDER of the mock assignments. This is how TypeMock works, each time MockManager.Mock is called the next constuctor is mocked and all expectations are tied to the specific instance.

Using this and the Firing Events techniques we can simulate different button sequences. 

// Mock ok Button Mock okButtonMock = MockManager.Mock(typeof(Button)); MockEvent clickOk = okButtonMock.ExpectAddEvent("Click"); // Mock cancel Button Mock cancelButtonMock = MockManager.Mock(typeof(Button)); MockEvent clickCancel = cancelButtonMock.ExpectAddEvent("Click"); // Mock ignore Button Mock ignoreButtonMock = MockManager.Mock(typeof(Button)); MockEvent clickIgnore = ignoreButtonMock.ExpectAddEvent("Click"); // run our code RunCodeThatCallsInitializeComponents(); // Test Button Clicks clickCancel.Fire(this,EventArgs.Empty);
4 comments
  1. Mock okButtonMock = MockManager.Mock(typeof(MenuItem);

    The code above, why use the type of “MenuItem” to mock button, that is a little bit confusing 🙂

  2. I shifted this SSH step to Diet Coda using the clipboard. We employed PasteBot through Tapbots to seize the true secret outside the clip-board in the Mac pc and set the idea from the clip-board in the apple ipad tablet.

Add Comment

Required fields are marked *. Your email address will not be published.