문제

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?

도움이 되었습니까?

해결책

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).

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top