在Flex、Actionscript中调用私有方法
我需要在 FlexUnit 中使用它来测试私有方法。是否有可能通过使用describeType通过反射来做到这一点,或者flexUnit可能有一些内置设施?我不喜欢人为限制我无法测试私有函数,这大大降低了灵活性。是的,这对我来说测试私有函数是很好的设计,所以请不要建议我重构我的代码。我不想为了单元测试而破坏封装。
I need it in FlexUnit to test private methods. Is there any possibility to do this via reflection by using describeType or maybe flexUnit has some build in facility? I dislike artificial limitation that i cannot test private functions, it greatly reduces flexibility. Yes it is good design for me to test private functions, so please do not advise me to refactor my code. I do not want to break the encapsulation for the sake of unit testing.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我 99% 确信这是不可能的,我很想知道你为什么要这样做。
您应该根据给定的输入对给定类的输出进行单元测试,无论类内部发生什么。您确实希望允许某人能够更改实现细节,只要它不更改预期输出(由单元测试定义)即可。
如果您测试私有方法,则对类的任何更改都将与单元测试紧密耦合。如果有人想要重新整理代码以提高可读性,或者进行一些更新以提高性能,他们将不得不更新单元测试,即使该类仍然按照最初设计的方式运行。
我确信在某些边缘情况下测试私有方法可能是有益的,但我预计在大多数情况下它是不需要的。您不必破坏封装,只需测试您的方法调用是否给出正确的输出......无论代码内部执行什么操作。
I'm 99% certain this isn't possible and I'm intrigued to know why you would want to do this.
You should be unit testing the output of a given class, based on given inputs, regardless of what happens inside the class. You really want to allow someone to be able to change the implementation details so long as it doesn't change the expected outputs (defined by the unit test).
If you test private methods, any changes to the class are going to be tightly coupled to the unit tests. if someone wants to reshuffle the code to improve readability, or make some updates to improve performance, they are going to have to update the unit tests even though the class is still functioning as it was originally designed.
I'm sure there are edge cases where testing private methods might be beneficial but I'd expect in the majority of cases it's just not needed. You don't have to break the encapsulation, just test that your method calls give correct outputs... no matter what the code does internally.
只需创建一个名为“unitTest”的公共方法,并在该方法中调用所有单元测试。当其中之一失败时抛出错误并从测试框架调用它:
Just create a public method called "unitTest" and call all your unit tests within that method. Throw an error when one of them fails and call it from your test framework:
您不能为此使用
describeType
。来自 Livedocs - flash.utils 包:
You cannot use
describeType
for that.From the Livedocs - flash.utils package:
当测试私有方法的冲动不可抗拒时,我只需为该方法创建一个可测试的命名空间。
在文件中声明一个命名空间,如下所示:
然后,您可以使用可测试作为要测试的方法的自定义访问修饰符,如下所示:
然后,您可以通过在测试中使用命名空间来访问该修饰符:
真的,虽然我认为这是提示您应该将功能拆分到一个单独的类中。
When the urge to test a private method is irresistible I just create a testable namespace for the method.
Declare a namespace in a file like this:
Then you can use the testable as a custom access modifier for the method you want to test like this:
You can then access that modifier by using the namespace in your tests:
Really though I think this is a hint that you should be splitting your functionality into a separate class.