0

I want to mock the singleton object? It seems that it's impossible in scalamock-3

I found that easyMock and powerMock can mock the singleton object (from https://github.com/fabura/scala-MockStaticObjects)

However, I cant get this work? Any ideas?

  • why do you need that? what problem are you trying to solve? – maks Feb 02 '16 at 08:12
  • I have a database singleton object, and I want to mock this database manager. – myregister0618 Feb 02 '16 at 08:25
  • 2
    Wouldn't it be better to create a trait which describes db operation and implement this trait in the singleton object? Thus you can mock just this trait – maks Feb 02 '16 at 13:01
  • Did you really mean scala 2.7.11? That's absolutely ancient and it's going to severely restrict what you can do with the language and ecosystem. – Daenyth Feb 04 '16 at 18:44

1 Answers1

0

If the singleton object has a static .getInstance method, it is fairly easy to mock.

You need to do the following at the top of your test class

@RunWith(PowerMockRunner.class) @PrepareForTest(Singleton.class)

then to mock the singleton

mockStatic(Singleton.class); Singleton mockSingleton = mock(Singleton.class); when(Singleton.getInstance()).thenReturn(mockSingleton);

any values you want to have the returned singleton to have I believe you have to set prior to the "when" Example: when(mockSingleton.toString()).thenReturn("I'm a mock");

Lencalot
  • 385
  • 2
  • 19