Results 1 to 3 of 3

Thread: Method with stateful dependency: how to unit test?

  1. #1
    Join Date
    Apr 2006
    Location
    Montreal, Canada
    Posts
    178

    Arrow Method with stateful dependency: how to unit test?

    Hi all,

    We have a method which explicitly instantiates an object with a state in order to complete its work, basically something like that:

    Code:
    public void someMethod(int arg0) {
      Helper h = new Helper(arg0);
      return h.help();
    }
    Our objective is to write a unit test for this method. As it is currently written, this method would not be tested in isolation since an instance of Helper is created. We therefore need to be able to replace Helper with a mock. Since Helper is maintaining some state and would not be thread-safe as a class attribute, moving it as an injectable dependency is not an option. I know that we could send arg0 as an argument to the help() method instead, but doing this in the real code would be somewhat problematic

    How should we go about testing this method? This is a fairly typical pattern, surely there must be a way to test it?

    Cheers,
    Spiff

  2. #2
    Join Date
    Aug 2004
    Posts
    2,715

    Default

    You could factor out the creation of the Helper into a separate method. So you would be able to override that method in a subclass (or use Spring's method replacement) to return a mock Helper instance.

    Regards,
    Andreas

  3. #3
    Join Date
    Apr 2006
    Location
    Montreal, Canada
    Posts
    178

    Default

    Yep, didn't think of that one. Works like a charm. Thanks!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •