0

I am new to JUnit testing. I want to mock a singleton class. The class looks like this.

public enum MockClass{
    INSTANCE;

    private MockClass(){
         //private constructor
    }

    public void convertToString(int a){
         return SomeClass.setString(a.toString());
    }

}

I want to mock this class such that whenever there is a call to MockClass.INSTANCE.convertToString(a), nothing should be executed. There is a function in PowerMockito called doNothing(). But what do I do for Singleton classes as shown above? In this case PowerMockito doesn't help.

Disclaimer: I cannot change the implementation of the class. It has to be enum. I am just unit testing the code developed by others.

Suhail Ahmed Khan
  • 405
  • 2
  • 5
  • 10
  • Note: you should not use enums to implement singleton pattern ;) – Ji aSH Apr 04 '16 at 12:49
  • In order to mock a class in JUnit, it needs to be extendable. An enum singleton does not meet this requirement. Consider using a different way of implementing this singleton so you can mock it. – abalos Apr 04 '16 at 12:52
  • 1
    Singletons are considered bad practice, see for instance http://c2.com/cgi/wiki?SingletonsAreEvil or http://stackoverflow.com/questions/137975/what-is-so-bad-about-singletons One of the reasons is because they make testing harder :) – Dawid Pytel Apr 04 '16 at 12:55
  • 1
    @Ash Effective Java 2nd Ed Item 3 explicitly advocates the use of enums to implement singletons: "a single-element enum type is the best way to implement a singleton". However, it also states "Making a class singleton can make it difficult to test its clients". – Andy Turner Apr 04 '16 at 12:57
  • See also: http://stackoverflow.com/questions/2302179/mocking-a-singleton-class – Jiri Tousek Apr 04 '16 at 13:00
  • @DawidPytel An overly broad statement. Singletons are heavily used in things like Spring, and have huge advantages when it comes to memory. – Christopher Schneider Apr 04 '16 at 13:37
  • @AndyTurner I'd say making an enum singleton is what makes it even more difficult, and there's no good reason to use an enum, despite some quote from a book. Mocking frameworks have no problem mocking classes with private constructors. In fact, it's easy to do that without any mocking framework. – Christopher Schneider Apr 04 '16 at 13:40
  • 1
    @ChristopherSchneider "and there's no good reason to use an enum" I never said there was, and I agree. I pointed out that a very experienced Java developer states that enums make things hard in this specific situation (he even writes it in bold, so he must really believe it); but using enums avoids some of the problems associated with singletons. – Andy Turner Apr 04 '16 at 13:43
  • Fair enough. Though the second quote in your comment reads However, it also states "Making a **class** singleton can make it difficult to test its clients" – Christopher Schneider Apr 04 '16 at 13:47

0 Answers0