Mock a superclass constructor

11,288

Solution 1

You could use PowerMock library. It is really a lifesaver when you need to accomplish things like yours. https://github.com/powermock/powermock/wiki/Suppress-Unwanted-Behavior

Solution 2

Mocking a constructor is a very bad idea. Doing so is circumventing behavior that will happen in production. This is why doing work in the constructor, such as starting threads and invoking external dependencies, is a design flaw.

Can you honestly say that the work performed in the constructor has no effect on the behavior you're trying to test? If the answer is no, you run the risk of writing a test that will pass in a test environment, but fail in production. If the answer is yes, that is a plain case for moving that "work" outside the constructor. Another alternative is to move the behavior you're trying to test to another class (maybe it's own).

This is even more true if you're using a DI framework like Guice (which I assume because you tagged it that way).

Share:
11,288
Rishi
Author by

Rishi

Updated on June 09, 2022

Comments

  • Rishi
    Rishi almost 2 years

    I would like to know if I can mock a super class constructors call and its super() calls.

    For example, I have the following classes

    class A
    {
        A(..)
        {
            super(..)
        }
    }   
    
    class B extends A
    {
        B(C c)
        {
            super(c)
        }
    }
    

    So, I am planning to unit test some methods in class B, but when creating an instance it does call the super class constructors making it tough to write unit tests. So, how can I mock all the super class constructor calls. Also I would like to mock few methods in class A so that it does return few values as I need.

    Thanks!!

  • jhericks
    jhericks about 12 years
    I wasn't aware of that part of the PowerMock library. I still think it points to a "smell" but just because something stinks doesn't mean you have the ability to actually clean it.
  • Chris Smowton
    Chris Smowton almost 8 years
    See above re: PowerMock. Regardless of whether it's a good idea or not, replacing a constructor at runtime is possible.