Skip to content

Instantly share code, notes, and snippets.

@loicdescotte
Last active March 25, 2023 12:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save loicdescotte/ce278a6783c1b293ce2c to your computer and use it in GitHub Desktop.
Save loicdescotte/ce278a6783c1b293ce2c to your computer and use it in GitHub Desktop.
class PrintService {
def print = println("I'm a real service")
}
trait Services {
val printService = new PrintService()
// put your other services here
}
//for example, a Play controller
class App (deps: Services) /*extends Controller*/ {
import deps._
def run = printService.print
}
// In Scala singletons (objects) can be parameterized, so no need for DI framework or container
object DependenciesModule extends Services //global object for your app or controller
object ServicesApp extends App(DependenciesModule)
ServicesApp.run //services
//testing
val printServiceMock = new PrintService { //or use Mockito
override def print = println("I'm a mock")
}
object MockServices extends Services {
override val printService = printServiceMock
}
object FakeServicesApp extends App(MockServices)
FakeServicesApp.run // "I'm a mock"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment