How to remove protected method on object in scala

Example:

object Test {

  def test = {
    doTest
  }

  protected def doTest = {
  // do something
  }
}

class MockTest extends WordSpec with Mockito{
  "" in {
    val t = spy(Test)

    // how do i stub out doTest?
  }
}

      

I have a Test class with a protected doTest method. How do I remove this protected method?

+3


source to share


2 answers


My advice would be to make the doTest

package private so that clients of your object cannot call it, but you should be able to test it from a single package.

package com.company.my.foo

object Test {

  def test = {
    doTest
  }

  private[foo] def doTest = {
  // do something
  }
}

      



and

package com.company.my.foo

class MockTest extends WordSpec with Mockito{
  "" in {
    val t = spy(Test)

    when(t.doTest()).thenReturn("foo")
  }
}

      

+1


source


Test

is a singleton (all Scala objects), you can subclass a class, but not an object. Hence, protected

it is a bit pointless here: you are saying that this method should only be available to subclasses, but it is not possible (since it Test

is an object).



You have several options depending on what suits your needs best. 1) you can make a Test

class and then extend it, or 2) change the access level doTest

to public

[which is the default in Scala if you did not specify an access modifier]

0


source







All Articles