3

Just started on unit testing using Scala and had this basic question.

class Test {
  ClassToBeTested testObject;

  @Before
  void initializeConstructor() {
    testObject = new ClassToBeTested(//Blah parameters);
  }

  @Test
  //Blah
}

The above example in Java shows that I can just declare an object of type ClassToBeTested and initialize it later. Can this be done in Scala? I tried it

class Test {
  var testObject = new ClassToBeTested()

  @Before def initializeConstructor() {
    //I do not know how to proceed here!!!!!!
  }

  @Test def testOne() {
    //Some test
  }
}

I don't want to do everything inside the testOne() because I want to use the object in different tests. The parameters of the constructor are mocks and in JUnit I know that mocks are not initialized if I initialize an object globally and not inside @Before.

soc
  • 27,983
  • 20
  • 111
  • 215
noMAD
  • 7,744
  • 19
  • 56
  • 94

1 Answers1

9

Here is how you can make it:

class Test {
  var testObject: ClassToBeTested = _

  @Before 
  def initializeConstructor() {
    testObject = new ClassToBeTested()
  }

  @Test 
  def testOne() {
    //Some test
  }
}

More on underscore init.


You can also read more about this in Section 18.2 Reassignable variables and properties of Programming in Scala book. Here is quote, that can be helpful to you:

More precisely, an initializer "= _" of a field assigns a zero value to that field. The zero value depends on the field's type. It is 0 for numeric types, false for booleans, and null for reference types. This is the same as if the same variable was defined in Java without an initializer.

Note that you cannot simply leave off the "= _" initializer in Scala. If you had written:

 var celsius: Float

this would declare an abstract variable, not an uninitialized one

Community
  • 1
  • 1
tenshi
  • 26,268
  • 8
  • 76
  • 90
  • I thougth scala cannot infer type when you initialize variable to default value by placing underscore. – om-nom-nom Aug 07 '12 at 19:24
  • Thanks!! So can this be used for normal variables also? Say, `var temp = _` and use this variable anywhere inside the class? – noMAD Aug 07 '12 at 19:29
  • 1
    @noMAD see my update. You can use it only for the class members, but not for the local variables - they should be always initialized. – tenshi Aug 07 '12 at 19:36