Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mockito and method access level

Tags:

java

mockito

My question is connected with framework Mockito and methods, which can be tested.

Public methods can be well tested.

Private methods cannot be tested in Mockito, but they can be tested in other mocking frameworks.

What with protected methods and methods without access level (package-private)? As I checked, protected methods can be tested by creating inherited subclass with public method. What is the best way of testing these methods?

like image 279
Pawel Avatar asked Feb 21 '26 17:02

Pawel


1 Answers

I'm not sure I understand the relationship to Mockito in this instance as if you're testing a method, you don't really want to mock that class. To answer your question, there are a couple of options:

For package-private, I always create my test cases in the same package as the class under test so I can access them.

For package-private or protected methods, you can use reflection to change the access level, but that's definitely a headache. What I would do is subclass and change the access level that way.

like image 111
Chris Thompson Avatar answered Feb 23 '26 06:02

Chris Thompson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!