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.
trait App extends DelayedInitNo explicit main method is needed. Instead, the whole class body becomes the “main method”. args returns the current command line arguments as an array.
Traits are used to share interfaces and fields between classes. They are similar to Java 8's interfaces. Classes and objects can extend traits, but traits cannot be instantiated and therefore have no parameters.
App is a trait which is utilized to rapidly change objects into feasible programs, which is carried out by applying DelayedInit function and the objects inheriting the trait App uses this function to execute the entire body of the program as a section of an inherited main method.
Scala provides a helper class, called App, that provides the main method. Instead of writing your own main method, classes can extend the App class to produce concise and executable applications in Scala.
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:
final val name = "Greg"
def name = "Greg"
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)If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With