Announcement Announcement Module
Collapse
No announcement yet.
Method with stateful dependency: how to unit test? Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • 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
    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

    Comment


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

      Comment

      Working...
      X