Testing private fields and methods - finally a solution!

Lots of people use Java reflection to access private methods for testing purposes (with JUnit, TestNG...). This is cumbersome and prevents refactoring (since methods must be accessed by Strings). Some other people change methods and fields from private to protected just to be able to test them, which is, of course, very undesirable.

This page explains the problem in detail.

There was no good solution until recently. But things have changed. Now, I am using the recently released dp4j library from K. Gabriele, an open-source annotation processor which lets me access any private constructors, methods and fields, only inside test methods (the ones marked with the @Test annotation or @InjectReflection). This library is now recommended by the JUnit website, and it works! It lets me test private methods, making testing much easier. Here it is:



The problem is that although the tests compile and run, yielding the right results, IntelliJ still underlines the private fields and methods as errors, and tells me: "XXX has private access".

I could put up with the red line errors (although I would prefer not), but the unacceptable side effect is that this prevents me to refactor the code, since IntelliJ will not refactor them in this state.

My question to you all is this:

        Is there a way to configure IntelliJ so that, inside of methods annotated with @Test, private fields and methods should be treated as if they were public (since now they can be accessed)? In more detail:

1) inside of methods annotated with @Test, private fields and methods should appear during the auto-complete (CTRL-SPACE).
2) inside of methods annotated with @Test, accessing private fields and methods should not marked as errors.
3) inside of methods annotated with @Test, we should be able to refactor private fields and methods (THIS IS THE MOST IMPORTANT).



public class ObjectToTestDp4j
    private int privateField;
    private ObjectToTestDp4j() { this.privateField = 123; }
    private int privateMethod() { return 456; }

public class TestAcessingPrivateObject {
    public void testAcessingObjectDP4J() throws Exception {
        ObjectToTestDp4j testObject = new ObjectToTestDp4j();
        assertEquals(123, testObject.privateField);
        assertEquals(456, testObject.privateMethod());


Thank you all,

Comment actions Permalink

Hi Marc,

It's not possible to configure IJ at the desired way at the moment. Feel free to submit corresponding request to the tracker but I doubt it will be solved without high interest from the community (roughly measured by number of votes/watches).


Comment actions Permalink

Please create an issue so we can vote on this. I think many developers can benefit from this (I sure can).

Thanks for posting. Cheers!

Comment actions Permalink

Ok! The issue is here:



Please sign in to leave a comment.