单元测试受保护的最佳方法是什么?Ruby 中的私有方法? [英] What's the best way to unit test protected & private methods in Ruby?

查看:85
本文介绍了单元测试受保护的最佳方法是什么?Ruby 中的私有方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用标准 Ruby Test::Unit 框架对 Ruby 中的受保护和私有方法进行单元测试的最佳方法是什么?

What's the best way to unit test protected and private methods in Ruby, using the standard Ruby Test::Unit framework?

我敢肯定有人会直言不讳地断言你应该只对公共方法进行单元测试;如果它需要单元测试,它不应该是受保护或私有的方法",但我并不真正感兴趣辩论那个.我有几个方法受到保护或私有有充分的理由,这些私有/受保护的方法比较复杂,并且类中的公共方法依赖于这些受保护/私有方法的正常运行,因此我需要一种方法来测试受保护/私有方法.

I'm sure somebody will pipe up and dogmatically assert that "you should only unit test public methods; if it needs unit testing, it shouldn't be a protected or private method", but I'm not really interested in debating that. I've got several methods that are protected or private for good and valid reasons, these private/protected methods are moderately complex, and the public methods in the class depend upon these protected/private methods functioning correctly, therefore I need a way to test the protected/private methods.

还有一件事...我通常将给定类的所有方法放在一个文件中,而该类的单元测试放在另一个文件中.理想情况下,我希望将这种受保护和私有方法的单元测试"功能实现到单元测试文件中,而不是主源文件中,以便使主源文件尽可能简单明了.

One more thing... I generally put all the methods for a given class in one file, and the unit tests for that class in another file. Ideally, I'd like all the magic to implement this "unit test of protected and private methods" functionality into the unit test file, not the main source file, in order to keep the main source file as simple and straightforward as possible.

推荐答案

您可以使用 send 方法绕过封装:

You can bypass encapsulation with the send method:

myobject.send(:method_name, args)

这是 Ruby 的一个特性".:)

This is a 'feature' of Ruby. :)

在 Ruby 1.9 开发过程中曾有过内部争论,认为 send 尊重隐私而 send! 忽略它,但最终在 Ruby 1.9 中没有任何改变.忽略下面讨论 send! 和破坏事物的评论.

There was internal debate during Ruby 1.9 development which considered having send respect privacy and send! ignore it, but in the end nothing changed in Ruby 1.9. Ignore the comments below discussing send! and breaking things.

这篇关于单元测试受保护的最佳方法是什么?Ruby 中的私有方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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