9

I'm trying to use scalatest to test an App like this:

object Main extends App {
    val name = "Greg"
}

class JunkTests extends FunSpec with MustMatchers {
    describe("Junk Tests") {
        it("Junk-1 -- Must do stuff") {
            println("Name: "+Main.name)
            // some test here
        }
    }
}

My name output is always null. How can I get my main object going to use its facilities during a test? In actual use I have an App that's an Http server and I want to send it messages, but right now its never initialized so the server is never started. This simple example shows that Main is never initialized.

om-nom-nom
  • 62,329
  • 13
  • 183
  • 228
Greg
  • 10,696
  • 22
  • 68
  • 98

1 Answers1

14

It should be noted that this trait is implemented using the DelayedInit functionality, which means that fields of the object will not have been initialized before the main method has been executed.

Scaladoc for App trait

So you can either:

  • define val as final: final val name = "Greg"
  • trigger main method before accessing name field
  • define name as method: def name = "Greg"
  • define name as lazy val: lazy val name = "Greg" (so in this case, as well as in previous, there is no matter in which order initialization is done)
om-nom-nom
  • 62,329
  • 13
  • 183
  • 228