There is such a problem. There is a singleton class whose instance is obtained via the getInstance () method and is further stored in the static field INSTANCE. And private static Input INSTANCE = getInstance();

When I try to do constructor.newInstance(); it first of all initializes static fields, and executes getInstance (), which in the case of testing cannot be called, I need only an empty instance. I want to direct the fields in it, and call up their complex getters.

    1 answer 1

    Singleton is considered an anti-pattern, also due to no testability.

    In terms of tests, singleton has at least 2 problems:

    • static initialization occurring during class loading (which you are facing)
    • It’s impossible to trivially (without ClassLoader magic, for example) reset the state of the singleton to the original between tests.

    To somehow test your class and save its properties, you can do the following:

    • Declare a public interface for business logic.
    • Logic to take out from singleton in a separate package-private class that implements this interface. Write tests for this class in the same package.
    • Singleton to use as a container for this class.

    enter image description here

    Alternative: use dependency injection or ServiceLocator.

    • I did without such a scheme. Just a class, where the getInstance () method and INSTANCE itself were called a holder, and all the stuffing was transferred to a package-private class, which is now easily instantiated and tested. And to set the field created a package-private setters. Now there is no reflection at all. But thanks for the idea. - Eugene