你能在scala中测试嵌套函数吗?
有没有办法测试嵌套函数(最好使用 ScalaTest)?
例如,有没有办法在下面的代码中测试 g()
:
def f() = {
def g() = "a string!"
g() + "– says g"
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
g
在f
之外不可见,所以我敢说不,至少在没有反射的情况下不可见。无论如何,我认为测试
g
会打破单元测试的概念,因为你永远不应该测试实现细节,而只应该测试公共 API 行为。如果f
测试失败,则跟踪g
中的错误是调试过程的一部分。如果测试
g
对您很重要,请将g
定义为f
外部的(受保护)方法。不过,这可能会破坏你的设计。另一个想法是在原始代码中调用
g
之后调用assert
。这将在测试期间执行,如果该属性不成立,则会引发异常,导致测试失败。它也会出现在常规代码中,但可以被编译器删除,因为assert
(及其同伴)是可消除的(参见例如 此处)。g
is not visible outside off
, 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 ing
is part of the debugging process if tests forf
fail.If testing
g
is important for you, defineg
as (protected) method outside off
. That might break your design, though.Another idea would be to put calls to
assert
after the call ofg
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 asassert
(and companions) are elidible (see e.g. here).您可以将方法设为 private[package-name] - 仍然会有点破坏设计,但保持其私有而不是受保护。
一般来说,我同意这样一个事实,即不应测试私有方法,但如果您维护编写得不好的代码...
现在在同一个包中进行测试(示例)可以测试 g()
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...
Now test in same package (example) could test g()