You do not have to leave your public method to be able to test it. Ideally, only public methods should be tested. If your method is private, it means that some public method will call it. You can perform the tests through the public method.
For example, imagine that this is your Base
class:
public class Base {
public int getNumero() {
return 2;
}
}
And this is your class DailyJob
:
public class DailyJob {
private Base getBaseId(int i) {
return new Base();
}
public int calculo(int i) {
Base base = getBaseId(i);
return base.getNumero() + 1;
}
}
You can perfectly perform your test using the calculo
method. Your test would be:
@Test
public void testCalculo() {
DailyJob d = new DailyJob();
int resultado = d.calculo(1);
int valorEsperado = 3;
assertEquals(resultado, valorEsperado);
}
If the method is complex and you really do need to create a test just for it, one strategy is to leave accessibility package
. However, the test class must be in the same package as the class to be tested. It is worth noting that regardless of this, it is interesting that test classes always fall into the same package as the class being tested.
If you are using some build manager like Maven or Gradle, they do a separation of folders for the codes and resources that should go into production and the codes and resources that are just for testing.
Both maven and gradle use src/main/java
as a directory for production and src/test/java
as a directory for testing. You can replicate the packages in the two folders, but both will not be considered as packages, just what is below them.
See image below:
Note that DailyJob
is in src/main/java
and DailyJobTest
is in src/test/java
. Despite this, both are within the same stackoverflow.dailyJobPackage
package. This way you will be able to access the methods quietly and they will remain invisible to the classes of the other packages. When the project is compiled the build manager will only use what is in src/main/java
to build.
Without using a build manager it is possible to achieve the same result, but you will have to do the configuration.