I'm writing a test method to reset the value of a singleton variable, however I have no clue how to do it. please can someone assist me with the test code to test the following:

public class Service extends CompositeService {

private static Service singleton;

public static Service get() {
    if (singleton == null) {
        singleton = new Service ();
    return singleton;

private Service () {}

If your test class needs to "interfere" with private variables that are not accessible through your class's public API, you should add the @TestVisible annotation:

private static Service singleton;

Your unit test can then do

Service.singleton = null;

when needed.

It's broadly preferable, where possible, to test using the public API, as this insulates your test class from the implementation details of your class and makes it run tests like any other consumer of the class's API. However, there are lots of situations, as it sounds like you've discovered, where it does become necessary to reach into the private state of a class during a test.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.