Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit test for Scala object (not class)

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?

like image 356
DilTeam Avatar asked Sep 16 '25 07:09

DilTeam


1 Answers

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 = ???
  }
like image 70
Maxim Avatar answered Sep 18 '25 10:09

Maxim