4

I've a singleton class in Scala that's declared as an 'object'. I need to write unit tests that 'mock' methods in this object. How do I do it? I tried using 'PowerMockRunner' etc with no luck.

For example:

object MyClass extends Serializable {
   def apply(): Unit = { ..... }
   def more methods....
}

Now I need to write a unit test that mocks the 'apply' method. How do I do it?

DilTeam
  • 2,551
  • 9
  • 42
  • 69
  • Please check out https://www.youtube.com/watch?v=ZasXwtTRkio. Note - although I did not understand this video the first 2-3 times that I saw it, I learned from it the value of simply passing arguments to a function (to achieve DI). You should not need to mock this method using some `mockito` trick. – Kevin Meredith Nov 24 '15 at 17:12

1 Answers1

3

The short answer - You shouldn't unit-test singletons.

The long is here - Unit testing with singletons.

You can extract the functionality to a trait and unit-test the trait.

Not sure why you need the extends Serializable but left it just to show what I mean

  object MyClass extends Serializable with TheFunctionality {
  // whatever you need here
  }

  trait TheFunctionality {
    def apply(): Unit = ???
  }
Community
  • 1
  • 1
Maxim
  • 7,268
  • 1
  • 32
  • 44