如何在 Scala 中测试对象的私有方法 [英] How to test an object's private methods in Scala

查看:129
本文介绍了如何在 Scala 中测试对象的私有方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个示例对象:

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

而且我想测试私有 sayFoo 方法而不使用以下解决方法:1. 没有将其定义为包私有2. 不将其定义为protected 而不是在测试类中继承它

And I want to test the private sayFoo method without the following workarounds: 1. Without defining it as package private 2. without defining it as protected and than inheriting it in the test class

我看到了一种可能的解决方案,即扩展 privateMethodTester 但它没有似乎只对类起作用.

I saw one possible solution which is to extend privateMethodTester but it doesn't seem to work for objects just classes.

现在,我知道有些人(如果不是很多)说您不应该测试私有方法,而应该只测试公共方法 (api).尽管如此,我仍然想测试它们.

Now, I know that some, if not many, say that you are not suppose to test private methods but rather only public ones (api). Nonetheless, I still do want to test them.

thx 进阶

推荐答案

无法通过任何标准方法进行测试.

It cannot be tested by any standard means.

但是,如果您需要覆盖"该部分代码,请测试在其实现中使用该私有方法的方法.这是间接的,当然,但它确实有效地测试了代码.

However, if you need to "cover" that section of code, then test the methods which use that private method in their implementation. It is indirect, granted, but it does effectively test the code.

例如,在您的类中,您可以使用另一种方法:

For example, in your class you could have another method:

def dontSayBar = {
    sayFoo()
    println("Other processing...")
}

如果经过测试,这将覆盖"私有方法中的代码.

and this will "cover" the code in the private method if tested.

附言一个好的经验法则是,如果您看到的代码没有出现在 coverage 运行中,那么您可能实际上并不需要该代码.

P.S. A good rule of thumb is that if you see code that isn't showing up in a coverage run, then you probably don't actually need that code.

这篇关于如何在 Scala 中测试对象的私有方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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