can you test nested functions in scala?

陌路散爱 提交于 2019-12-05 18:16:01

问题


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"
}

回答1:


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



来源:https://stackoverflow.com/questions/5333298/can-you-test-nested-functions-in-scala

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!