9

How to unit test private (means with package visibility) classed in java?

I have a package, only one class is public in this package, other classes are private. How to cover other classed with unit tests? I would like to include unit tests in resting jar.

Kowser
  • 8,123
  • 7
  • 40
  • 63
Sergey Pereverzov
  • 124
  • 1
  • 1
  • 3
  • are they private or package private? If they are package private, then you can test them like any other class, provided your tests are in the same package (which they should)... – assylias Aug 29 '13 at 09:38

3 Answers3

14

Create the unit test class in the same package.

For example, If com.example.MyPrivateClass located in src/main/java/com/example/MyPrivateClass.java

Then the test class will be in same package com.example.MyPrivateClassTestCase and will be located in src/test/java/com/example/MyPrivateClassTestCase.java

Samiron
  • 5,169
  • 2
  • 28
  • 55
Kowser
  • 8,123
  • 7
  • 40
  • 63
4

There are two ways to do this.

The standard way is to define your test class in the same package of the class to be tested. This should be easily done as modern IDE generates test case in the same package of the class being tested by default.

The non-standard but very useful way is to use reflection. This allows you to define private methods as real "private" rather than "package private". For example, if you have class.

class MyClass {
    private Boolean methodToBeTested(String argument) {
        ........
    }
}

You can have your test method like this:

class MyTestClass {

    @Test
    public void testMethod() {
        Method method = MyClass.class.getDeclaredMethod("methodToBeTested", String.class);
        method.setAccessible(true);
        Boolean result = (Boolean)method.invoke(new MyClass(), "test parameter");

        Assert.assertTrue(result);
    }
}
KKKCoder
  • 903
  • 9
  • 18
3

As indicated in @Kowser's answer, the test can be in the same package.

In Eclipse, and I assume other IDEs, one can have classes in different projects but in the same package. A project can be declared to depend on another project, making the other project's classes available. That permits a separate unit test project that depends on the production project and follows its package structure, but has its own root directory.

That structure keeps the test code cleanly separated from production code.

Patricia Shanahan
  • 25,849
  • 4
  • 38
  • 75