Let's say I have a class like this:
public class ClassA
{
[...]
protected void methodIWantToTest()
{
[...]
}
[...]
}
When I a write a unit test in IntelliJ Idea 13, I don't get compiler errors, when I write something like:
public class ClassATest
{
@Test
public void test()
{
final ClassA objectUnderTest = new ClassA();
objectUnderTest.methodIWantToTest(); // Why can I access a protected method here?
}
}
methodIWantToTest
is protected. Why can I access it in a test?
To test a protected method using junit and mockito, in the test class (the class used to test the method), create a “child class” that extends the protagonist class and merely overrides the protagonist method to make it public so as to give access to the method to the test class, and then write tests against this child ...
The protected access modifier is accessible within the package. However, it can also accessible outside the package but through inheritance only. We can't assign protected to outer class and interface. If you make any constructor protected, you cannot create the instance of that class from outside the package.
To access a protected method, inherit a class from this calls and then create and instance of the chold class and then using the instance object, call the protected method.
In most cases, you do not want to write tests for non-public methods, because that would make the tests dependent on the internal implementation of a class. But there are always exceptions.
Because the classes are in the same package (even though different folders). Classes in the same package as well as subclasses can access protected methods.
This is not a junit oddity or anything to do with the ide. It's just protected
doing what protected
does when you have the classes in the same package (which presumably you must).
Access Levels
Modifier Class Package Subclass World
public Y Y Y Y
protected Y Y Y N
no modifier Y Y N N
private Y N N N
https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
This differs from other languages definitions of protected
such as c#
for example where protected
means only the class and it's subtypes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With