How to mock protected method in Java

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • intelrate
    New Member
    • Jun 2009
    • 3

    How to mock protected method in Java

    Here is a question.

    I wanted my JUnit tests to be more modular and found how to mock protected methods for that purpose. Briefly speaking, we cannot mock and control calls of protected method with JDK dynamic proxy because protected methods are not in any interface but we can create MockInterface with mock method under control and call it from overridden protected method to achieve our goal.

    The problem I’m trying to resolve now is that my mock method should have the same number of parameters as protected method I want to mock. It forces me to create several mock methods with different number of parameters which is not elegant. Does anyone know better solution in JMock or other Java framework? Any help would be very appreciated.
  • JosAH
    Recognized Expert MVP
    • Mar 2007
    • 11453

    #2
    Extend your class and override your protected method by a public one; test your extended class and your overriding public method.

    kind regards,

    Jos

    Comment

    • intelrate
      New Member
      • Jun 2009
      • 3

      #3
      Thank you JosAH

      That's what I'm doing right now. The problem is that if my protected method has 2 arguments then my mock method should be like

      Object mockMethod(Obje ct parameter1, Object parameter2);

      If I need to mock another protected method with 3 parameters then I have to create

      Object mockMethod(Obje ct parameter1, Object parameter2, Object parameter3);

      It works for me but probably there is another approach to mock protected methods which I don't know about.

      Cheers!

      Comment

      • JosAH
        Recognized Expert MVP
        • Mar 2007
        • 11453

        #4
        Originally posted by intelrate
        It works for me but probably there is another approach to mock protected methods which I don't know about.
        Not that I know of but you shouldn't mock protected methods in the first place; you should mock the API of the class (the methods published in its interface).

        kind regards,

        Jos

        ps. Was this just a 'pro forma' question? You already turned it into a blog entry ...

        Comment

        • intelrate
          New Member
          • Jun 2009
          • 3

          #5
          Originally posted by JosAH
          Was this just a 'pro forma' question?
          Actually I'm not totally happy with the solution I have but for now it should be fine.

          Thanks.

          Comment

          Working...