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
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 by tolisss (28.8k 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 by richard (3.9k 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 by tolisss (28.8k 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 by richard (3.9k points)
0 votes
aha that is very cool :)
thnks a lot for supporting!!!
answered by tolisss (28.8k points)
...