简体   繁体   中英

Mock Static Enum Inside Final Class

there is a class X;

public final class X {
    private X() {}
    ...
    public static enum E {
        thingA("1"),
        thingB("0")

        public boolean isEnabled(){...}
    }
    ...
}

in some another class there a method M

public class AnotherClass{

    public void M(){
        if (E.thingB.isEnabled()) {
            doSomething();
        }
    }
    ...
}

i want to test M method, is it possible to use mockito/powermockito to mock statement within if. to do something like this

 when(E.thingB.isEnabled()).thenReturn(true)?

Regardless of whether the enum is nested or not, you can't create or mock a new instance of an enum. Enums are implicitly final , and more importantly, it breaks the assumption that all instances of the enum are declared within the enum.

An enum type has no instances other than those defined by its enum constants. It is a compile-time error to attempt to explicitly instantiate an enum type. ( JLS )

Because all instances of the enum are known at compile time, and all properties of those instances are likewise predictable, usually you can just pass in an instance that matches your needs without mocking anything . If you want to accept an arbitrary instance with those properties, have your enum implement an interface instead.

public interface I {
    boolean isEnabled();
}

public enum E implements I {  // By the way, all enums are necessarily static.
    thingA("1"),
    thingB("0");

    public boolean isEnabled(){...}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM