@VisibleForTesting的替代方法 [英] Alternatives to @VisibleForTesting

查看:1411
本文介绍了@VisibleForTesting的替代方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道@VisibleForTesting是不可取的,因为它仅出于测试目的而更改类的接口。理想情况下,我们应该测试我们实际使用的接口。但是什么是更好的选择?

I understand that @VisibleForTesting is not desirable because it changes the interface of a class just for testing purposes. Ideally we should test the interface that we actually use. But what would be a good alternative?

推荐答案

您使用 @VisibleForTesting 如您所说,何时要测试不向最终用户公开的部分代码。如果您想对其进行测试,则很可能意味着它很复杂,或者至少是微不足道的。两种解决方案是:

You use @VisibleForTesting when, as you said, you want to test a part of code you're not exposing to the end user. If you want to test it then it most likely means it's complicated, or at least not trivial. Two solutions would be:


  1. 将要调用的方法拆分为几种方法,这样对于没有一个大方法会更加自在

  2. 查看是否可以将行为转移到负责该行为的外部对象上。

当事情开始变得复杂时,我非常喜欢#2,因为我可以拥有一个可以测试的外部对象,并确保它可以正常工作而不必通过我们的界面来显示。

I like #2 a lot when stuff starts getting complicated, since I can have an external object that I can test and make sure it works without having to expose it through our interface.

话虽如此,有时行为并不保证将方法提取到新对象中,而您使用 @VisibleForTesting 只是为了节省时间。经验告诉您何时应该这样做(或不值得)。

Having said that, some times the behaviors don't warrant the extraction of the method into a new object and you use @VisibleForTesting just to save time. Experience is what tells you when it's worth it to do it (or not).

这篇关于@VisibleForTesting的替代方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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