Search code examples
scalascalatest

How to call App object from inside of tests


I have an object that extends the App trait, and I want to write some tests that use this object. E.g.

object EntryPoint extends App {
  println("running the app")
  // runs misc code
}

I want to write something like:

class EntrySpec extents FlatSpec {
  val entryPoint = EntryPoint(Array("Some arg"))
  // do stuff with the entrypoint object
}

But when I try to do this, I cant seem to access the EntryPoint object in my test. All other objects and classes resolve normally. What is going wrong here?


Solution

  • Just write with .main(..) in EntrySpec

    /src/main/scala/EntryPoint.scala

    object EntryPoint extends App {
      println(s"running the app, args=${args.mkString}")
    }
    

    /src/test/scala/EntrySpec.scala

    import org.scalatest.FlatSpec
    
    class EntrySpec extends FlatSpec {
      EntryPoint.main(Array("Some arg")) // prints "running the app, args=Some arg"
    
      assert(1 + 1 === 2)
    }
    

    Everything should work.