开发者

can you test nested functions in scala?

开发者_JS百科Is there any way to test a nested function (ideally with ScalaTest)?

For example, is there a way to test g() in the below code:

def f() = {
  def g() = "a string!"
  g() + "– says g"
}


g is not visible outside of f, so I daresay no, at least not without reflection.

I think testing g would break the concept of unit testing, anyway, because you should never test implementation details but only public API behaviour. Tracking an error to a mistake in g is part of the debugging process if tests for f fail.

If testing g is important for you, define g as (protected) method outside of f. That might break your design, though.

Another idea would be to put calls to assert after the call of g in the original code. This will be executed during tests and raise an exception if the property does not hold, causing the test to fail. It will be there in regular code, too, but can be removed by the compiler as assert (and companions) are elidible (see e.g. here).


You could make method private[package-name] - still breaks design a bit, but keeps it private instead of protected.

Generally I agree with the fact that one should not test private methods, but if you are maintaining poorly written code...

private[example] def g() = "a string!"

def f() = {
  g() + "– says g"
}

Now test in same package (example) could test g()

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜