You don’t need 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 some public method will call you. You can perform the tests through the public method.
For example, imagine that this is your class Base
:
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 through the method calculo
. 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 it is really necessary to create a test just for it, one strategy is to leave the accessibility package
. However, the test class needs to be in the same package as the test class. It is worth noting that regardless of this, it is interesting that the test classes always stay in the same package of the class being tested.
If you’re using some build manager like Maven or Gradle, they sort folders for codes and Resources that should go to production and 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 test directory. You can replicate the packages in both folders, but both will not be considered as packages, only what is below them.
See image below:
Realize that DailyJob
is in src/main/java
and DailyJobTest
is in src/test/java
. Despite this, they are both within the same package stackoverflow.dailyJobPackage
. Then 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 on src/main/java
to build.
Without using a build manager it is possible to achieve the same result, but you will have to make the configuration.
Cool Victor, with the extra answers you linked there, all my doubts have been resolved. Thank you very much!
– user94991