1

I have the following enum in java:

public enum MyEnum {
    INSTANCE;
    //do some other stuff
    public List<Long> getBlah(String input) {
        return something;
    }
}

The following is the test code in scala (Why in scala? because the actual code that uses MyEnum is in scala)

import org.powermock.api.mockito.PowerMockito.mock
import org.powermock.modules.junit4.PowerMockRunner
import org.powermock.core.classloader.annotations.PrepareForTest
import org.powermock.reflect.Whitebox

@RunWith(classOf[PowerMockRunner])
@PrepareForTest(Array(classOf[MyEnum]))
class MyTest extends FunSuite {
    test("my test") {
        var myMock = mock(classOf[MyEnum])
        Whitebox.setInternalState(classOf[MyEnum], "INSTANCE", myMock)
        var result = MyEnum.INSTANCE.getBlah("input")
}
}

But I get the error:

java.lang.IllegalArgumentException: Cannot subclass final class class MyEnum

The same test code works in junit but not in scala. I suspect that its scala specific. Can anyone point the mistake? I think its the RunWith and PrepareForTest annotations that are not working.

Angel Cuenca
  • 1,637
  • 6
  • 24
  • 46
kk1957
  • 8,246
  • 10
  • 41
  • 63
  • Why `Array(classOf[MyEnum])`? Also, you can't subclass an enumeration, so subclassing `MyEnum` seems strange (though you should, in theory, be able to do this). What are you trying to test for here, that just passing the actual enumeration won't suffice? – Nathaniel Ford Aug 25 '16 at 22:58
  • Array(classOf[MyEnum]) is required as that is the syntax. That is the whole purpose of this question that something that I can do easily in java, I am not able to do in scala. I am unit testing my logic, MyEnum contains code with a call to the database and hence it needs to be mocked. – kk1957 Aug 26 '16 at 00:02
  • Still curious what you're trying to accomplish. These questions all indicate this is either unsolved or really hairy even in Java: [this](http://stackoverflow.com/questions/34515740/scala-powermockito-java-final-classes-causing-build-error-in-scala-tests-usi), [this](http://stackoverflow.com/questions/2302179/mocking-a-singleton-class) and [this](http://stackoverflow.com/questions/15939023/how-to-mock-an-enum-singleton-class-using-mockito-powermock). – Nathaniel Ford Aug 26 '16 at 00:11
  • As I said before, I am trying to mock a singleton/final class using scala. The code that I have pasted works in java - I have it running in my environment. Not scala. You cannot mock enum using Mockito, but using PowerMock its all possible. – kk1957 Aug 26 '16 at 13:56
  • @kk1957 did you get any solution to this – gursahib.singh.sahni Jul 04 '17 at 11:24
  • @gursahib.singh.sahni no, its sitting in my backlog – kk1957 Jul 04 '17 at 15:19

0 Answers0