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.

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

3 Comments

I thougth scala cannot infer type when you initialize variable to default value by placing underscore.
Thanks!! So can this be used for normal variables also? Say, var temp = _ and use this variable anywhere inside the class?
@noMAD see my update. You can use it only for the class members, but not for the local variables - they should be always initialized.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.