Welcome to Typemock Answers. Here you can ask and receive answers from other community members. And if you liked or disliked an answer or thread: react with an up- or downvote Enjoy!

Mock the 3rd instance on the row

0 votes
With MockManager.Mock we can mock the next created instance but if i want to mock only the next after next instance can I?
asked Feb 4, 2005 by tolisss (3,660 points)

4 Answers

0 votes
With MockManager.Mock we can mock the next created instance but if i want to mock only the next after next instance can I?

It is actually quite simple. You mock all 3 instances but add expectations only for the third instance:

Here is an example:
// No expectations: will run all normal -for first 2 instances
MockManager.Mock(typeof(YourClass));
MockManager.Mock(typeof(YourClass));
// Mock and add expectations for 3rd instance
Mock mock MockManager.Mock(typeof(YourClass));
mock.Expect....
answered Feb 4, 2005 by richard (3,900 points)
0 votes
But if all instances are private ?e.g created inside a method that i m testing i can not do that then :(
answered Feb 4, 2005 by tolisss (3,660 points)
0 votes
This is exactly TypeMock's value, you can mock *future* instances .
So if you have this code in class TestedClass
class TestedClass
{
  int something;
  public void PublicMethod()
  {
     PrivateMethod(); 
  }
  private void PrivateMethod()
  {
    YourClass c1 = new YourClass();
    YourClass c2 = new YourClass();
    YourClass c3 = new YourClass();
    something = c3.DoSomething();
  }


And you want to mock the 3rd instance (c3) that DoSomething should return 5 for example, you can do it like this
// No expectations: will run all normal -for first 2 instances 
MockManager.Mock(typeof(YourClass)); 
MockManager.Mock(typeof(YourClass)); 
// Mock and add expectations for 3rd instance 
Mock mock MockManager.Mock(typeof(YourClass)); 
mock.ExpectAndReturn("DoSomething",5);
TestedClass t = new TestedClass();
t.PublicMethod();


Now the TestedClass.something will equal 3.
answered Feb 4, 2005 by richard (3,900 points)
0 votes
aha that is very cool :)
thnks a lot for supporting!!!
answered Feb 4, 2005 by tolisss (3,660 points)
...