How to test an object's private methods in Scala

后端 未结 3 1855
醉话见心
醉话见心 2021-01-07 09:24

I have an example object:

object Foo {
  private def sayFoo = \"Foo!\"
}

And I want to test the private sayFoo method without the following

3条回答
  •  孤独总比滥情好
    2021-01-07 09:56

    Probably someone has done this already: How about an annotation macro @Testable that emits the object with a method that exposes the private members, but only when compiling for testing (and just the object otherwise).

    scala> object X { private def f = 42 ; def g = 2 * f }
    defined object X
    
    scala> X.g
    res1: Int = 84
    
    scala> object X { private def f = 42 ; def g = 2 * f ; def testable = new { def f = X.this.f } }
    defined object X
    
    scala> X.testable.f
    warning: there was one feature warning; re-run with -feature for details
    res2: Int = 42
    
    scala> object X { private def f = 42 ; def g = 2 * f ; def testable = new Dynamic { def selectDynamic(name: String) = X.this.f } }
    defined object X
    
    scala> X.testable.f
    warning: there was one feature warning; re-run with -feature for details
    res4: Int = 42
    

    Alternatively, it could emit a different object TestableX.

提交回复
热议问题