0

Java Question: I am working on a class (call it ProcessorA that only extends Object. It is also stateless). It will reside in a Spring Service on a Web Server. The class declares several public methods as the class' API.
I want to test this class with a simple JUnit test. I need to test some functionality that is a few method calls deep inside of 1 public method. However, between the API Method and the method to test there are several classes would be loaded at runtime by Spring in the Web Server. I can completely by-pass this by declaring the method to be tested as a 'default' method and calling it directly from an instance (of ProcessorA) from the JUnit test.
I have been told that this is NOT a best practice.
However, I am at a loss as to exactly what is gained by further restricting access to the method to be tested. So, what is it that can be gained by declaring a method as private over default (which is more restrictive than "protected" (which by inclusion is also verboten). \

public class ProcessorA {
    public methodA(String input) throws ValidationException {
        doSomeValidationStuff(input);
        doStuffToTest(input);
    }
    private doSomeValidationStuff(String input) throws ValidationException {
        //Libraries that are not loaded at execution and not available for the JUnit test
    }
    doStuffToTest(String input) {
        //Code to be tested}
    }
}

class MyJunitTest {
    @Test
    void doStuffToTestTest() {
        ProcessorA processorA = new ProcessorA();
        String testData = "test data String";
        assertNotNull( processorA.doStuffToTest(testDate));
    }
}

The answer that I am looking for isn't for how to get around this constraint, but what is gained by blindly following a blanket directive that has (seemingly) no payoff.

Progman
  • 16,827
  • 6
  • 33
  • 48
Cody
  • 13
  • 4
  • 1
    You might want to check other questions like https://stackoverflow.com/questions/105007/should-i-test-private-methods-or-only-public-ones – Progman Aug 02 '22 at 19:20

1 Answers1

0

Default scope in Java is a package-private scope which means that all classes from the same package can use this method. If you restrict it to private, only methods from the same class can do it. This is what we gain. It is your decision, do you need to expose this method to other classes or it is enough to just keep it private but don't expose something only for testing purposes.

pholak
  • 158
  • 1
  • 8