By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
448,485 Members | 1,031 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 448,485 IT Pros & Developers. It's quick & easy.

How to mock protected method in Java

P: 3
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.
Jun 11 '09 #1
Share this Question
Share on Google+
4 Replies

Expert 10K+
P: 11,448
Extend your class and override your protected method by a public one; test your extended class and your overriding public method.

kind regards,

Jun 11 '09 #2

P: 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(Object parameter1, Object parameter2);

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

Object mockMethod(Object 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.

Jun 12 '09 #3

Expert 10K+
P: 11,448
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,


ps. Was this just a 'pro forma' question? You already turned it into a blog entry ...
Jun 13 '09 #4

P: 3
Actually I'm not totally happy with the solution I have but for now it should be fine.

Jun 13 '09 #5

Post your reply

Sign in to post your reply or Sign up for a free account.