Static import of static Nested class not working

289 views Asked by At
package com.foo;
public abstract class A {
    private functionA() {
    }
  static class B {
     A a;
     public functionB() {
       a.functionA();
     }
}

So, I need to test functionA() from a different package but I can't make any changes in class A, or the package com.foo that is the constraint. I am trying to do a static import so that I can access static nested class B from outside this package but it gives me the error of "cannot find symbol, symbol: static B, class A" I have tried import static com.foo.A.* also but on writing B.functionB() inside Test class I get the error "cannot find symbol B inside Test Class". Please find the Test class syntax below:

package com.foo.test;
import static com.foo.A.B;
public class Test {
   B.functionB(); 
}

Is there any other way that I can test functionA() or functionB() from outside the package?

1

There are 1 answers

4
MusicMan On

You cannot call the outer class's instance method from a static inner class.

There are two ways you could go about this:

  1. Rather than test the private function directly, call a public method that calls the private function and analyze the side effects. In fact, at the end of the day, sticking with public methods is better for black-box testing.
  2. You can put your test class in the same package, but in a different source folder. This is how a lot of IDEs handle it by default (src/main/java for your main code, src/test/java for unit tests). Note that your functionA() method must be package protected instead of private for this (i.e. remove the private keyword).

That said, if you have your heart set on your current way, you can just make B and functionB public and add the static modifier to functionB, and it should work as long as functionB has access to an instance of A. Of course, this sort of defeats the point of making functionA private.