Java Mailing List Archive

http://www.gg3721.com/

Home » user.jmock »

[jmock-user] How to Spy a Method

DispatchMediaGroup

2011-11-15

Replies: Find Java Web Hosting

Author LoginPost Reply

Hey all, need a little help here.

I've been writing unit tests now for about a month or so, retroactively.
That is, we are trying to get to a test-driven development paradigm, but for
now, we need to cover our existing code base. We are using JUnit 3 and
JMock 2.5.1.

The issue is as such:

I have a method of a class that I wish to test. It does certain things
depending on parameter state, like any good ole method. However, at the end
of this method's execution, it daisy-chains to another method. This second
method is not one that we wish to test, especially as its code just creates
an HTTP connection to a URL and posts a message there. I want to write my
tests and expectations in such a way that I can expect the method
invocation, but not actually execute the code in that method.

Now, having done quite a bit of reading and Googling about this, I have not
been able to find the answer I need, but what I want to do is apparently
called 'method spying'. Any idea how to do this? This is a scenario where
I must stay within the constraints of the existing environment (no new jars,
no new frameworks - just JUnit and JMock).

Example:

public class SomeClass
{
  private static final SomeClass INSTANCE = new SomeClass();

  private SomeClass()
  {}

  public static SomeClass getInstance()
  {
      return INSTANCE;
  }

  protected void methodOne(Object objects...)
  {
      // do some stuff

      if (somethingIsTrue)
      {
         // This is the method invocation I want to expect, but not
execute
         methodTwo();
      }

      // do more stuff
  }

  protected void methodTwo(Object objects...)
  {
      // Here's my crappy workaround for the time-being:
      if (!System.getProperty("isTestCase").equals("true"))
      {
         // make a bunch of calls that shouldn't be tested
         // if executed, timeout and break test(s)

         // now i've broken some encapsulation
         // i've also introduced bad coding/testing practices
         // writing code just to be able to test is not okay (as
opposed to writing testable code)
      }
  }
}
--
Sent from the jMock - User mailing list archive at Nabble.com.


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

  http://xircles.codehaus.org/manage_email


©2008 gg3721.com - Jax Systems, LLC, U.S.A.