I have this example class
class Foo extends Parent {
final override protected def test(): String = "hello world"
}
As it is now, I am unable to call this method directly within my unit test. I am using Mockito and from what I've read so far, I either need to
- remove the
final
so I can extend and override the access modifier (turn protected to private[package]) with another child class (Bar extends Foo) - update the Foo class to be
private[package]
.
Neither options are desirable. Is there a way to keep the signature while still exposing the method to be unit testable?
CodePudding user response:
You can make test
indirectly accessible by extending Foo
in the test with a subclass declaring a public method that calls test
.
You didn't mention which test execution framework you're using, but here's an example using ScalaTest with the FlatSpec
style:
import org.scalatest.flatspec.AnyFlatSpec
class FooSpec extends AnyFlatSpec {
class TestingFoo extends Foo {
def accessibleTest: String = test
}
it should "say hello" in {
assert(new TestingFoo().accessibleTest == "hello world")
}
}
The overall approach would be similar with other testing frameworks.