Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can I access a protected method in a test?

Tags:

java

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?

like image 813
Dmitrii Pisarenko Avatar asked Nov 12 '14 18:11

Dmitrii Pisarenko


People also ask

How do you access protected methods in test class?

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 ...

Where can a protected method be accessed from?

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.

How do I access a protected method in SAP?

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.

Can we write test cases for protected methods?

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.


2 Answers

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.

like image 200
Jeff Storey Avatar answered Oct 24 '22 01:10

Jeff Storey


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.

like image 31
weston Avatar answered Oct 23 '22 23:10

weston