Mocking constructor - is it possible?

View: New views
2 Messages — Rating Filter:   Alert me  

Mocking constructor - is it possible?

by Hr Borisov :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

I have the following question: When we have a local object for a method and we
invoke a constructor for that object, can we catch the invocation to the
constructor and mock the creation of the object?
I know that I can make a mock of the invocation of some method in a class not
depending on the reference but it would not help me. For example if I want to
mock isEmpty() method of some collection object I could not because I can't
calculate the consecutive number of the invocation that is important to me.
Thanks in advance!

Example:

Class A {
  void someMethod() {
    B ref = new B();

    if (ref.doSomething() == 10) {
      // I want to get here by mocking ref
    }
  }
}

Class B {
  int doSomething() {
   ...
  }
}



---------------------------------------------------------------------
To unsubscribe from this list, please visit:

    http://xircles.codehaus.org/manage_email



Re: Mocking constructor - is it possible?

by Steve Freeman-2 :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

We can't do that. We usually find that whatever made us think of doing  
so is not the best design, and try another direction. If you could  
give us a more concrete example, we might be able to help you better.

S.

On 23 Oct 2009, at 14:32, Hr Borisov wrote:

> I have the following question: When we have a local object for a  
> method and we
> invoke a constructor for that object, can we catch the invocation to  
> the
> constructor and mock the creation of the object?
> I know that I can make a mock of the invocation of some method in a  
> class not
> depending on the reference but it would not help me. For example if  
> I want to
> mock isEmpty() method of some collection object I could not because  
> I can't
> calculate the consecutive number of the invocation that is important  
> to me.
> Thanks in advance!
>
> Example:
>
> Class A {
>  void someMethod() {
>    B ref = new B();
>
>    if (ref.doSomething() == 10) {
>      // I want to get here by mocking ref
>    }
>  }
> }
>
> Class B {
>  int doSomething() {
>   ...
>  }
> }
>

Steve Freeman

Winner of the Agile Alliance Gordon Pask award 2006
Book: http://www.growing-object-oriented-software.com

+44 (0) 797 179 4105
M3P Limited.  http://www.m3p.co.uk
Registered office. 2 Church Street, Burnham, Bucks, SL1 7HZ.
Company registered in England & Wales. Number 03689627




---------------------------------------------------------------------
To unsubscribe from this list, please visit:

    http://xircles.codehaus.org/manage_email