Question

I'm testing a method I added to a scala class whose constructor is marked as private. It is accessed via a singleton Object, which does tons of other things that I don't want to touch.

class DummyClass private (config: DummyConfig) extends Runnable {

   def refresh() = {
       // Does tons of things
   }

   def updateProperty() = {
      // My method
   }
}

Object DummyClass {
  def apply(config: DummyConfig) = {
     val clss = new DummyClass(config)
     clss.refresh()
     new Thread(clss).start()
     clss
  }
}

In my JUnit (Specs/Mockito), I just want to create an object of that class and test the single method that I added, without it calling refresh or starting a thread.

Even when I add guava's annotation @VisibleForTesting over class DummyClass, I'm not able to use the constructor in the JUnit test. Is there a way I can achieve that?

Was it helpful?

Solution

Where is this @VisibleForTesting annotation coming from? Is it the one provided by the Guava library?

Most likely, this is just an informative annotation, just used to document the fact that you gave a more relaxed visibility to a method/constructor simply to allow unit testing.

In your case you would have to actually change the visibility of the constructor:

package p

class DummyClass private[p] (config: DummyConfig) extends Runnable {

   def refresh() = {
       // Does tons of things
   }

   def updateProperty() = {
      // My method
   }
}

Here if you put your unit test in the package p you can access the constructor since it is now package private. Add the annotation to indicate that no production code is allowed to call the constructor (but again, it will depend on the good behavior of the other developers working on the project, the compiler will not enforce anything based on the annotation).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top