你能在 Scala 中测试嵌套函数吗? [英] can you test nested functions in scala?

查看:34
本文介绍了你能在 Scala 中测试嵌套函数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法测试嵌套函数(最好使用 ScalaTest)?

Is there any way to test a nested function (ideally with ScalaTest)?

例如,有没有办法在下面的代码中测试g():

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

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

推荐答案

gf 之外是不可见的,所以我敢说不,至少在没有反射的情况下不会.

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

我认为测试 g 会打破单元测试的概念,无论如何,因为你永远不应该测试实现细节,而应该只测试公共 API 行为.如果 f 的测试失败,跟踪 g 中的错误是调试过程的一部分.

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.

如果测试 g 对您很重要,请将 g 定义为 f 之外的(受保护的)方法.不过,这可能会破坏您的设计.

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

另一个想法是在原始代码中调用 g 之后调用 assert.这将在测试期间执行并在属性不成立时引发异常,导致测试失败.它也会出现在常规代码中,但可以被编译器删除,因为 assert(和伴随)是可删除的(参见例如 这里).

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

这篇关于你能在 Scala 中测试嵌套函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆