作为包装器的静态方法

发布于 2024-12-12 07:23:57 字数 366 浏览 0 评论 0原文

如果您有一个名为 MyClass 的类,其中包含一组公共方法;方法A、方法B和方法C。在应用程序的某些位置,您只需要 MyClass 中的一个方法,例如:

MyClass myClass = new MyClass();
myClass.MethodA();

为了简化上述内容,我想创建一个包装上述代码行的静态方法。我计划针对 MethodA 编写单元测试。在我的单元测试中,MethodA 与使用模拟框架实现的接口进行交互(我认为这称为控制反转)。

是否可以安全地假设通过测试 MethodA 静态方法(包装方法)也被间接测试。我假设 MethodA 中使用的接口的实际实现也正在测试中。

或者我不应该实现静态方法?

If you have a class called MyClass with a set of public methods; MethodA, MethodB and MethodC. And in some locations of an application you only need a single method from MyClass, for example:

MyClass myClass = new MyClass();
myClass.MethodA();

To simplify the above I would like to create a single static method that wraps the above lines of coded. I am planning to write unit tests against MethodA. In my unit test MethodA interacts with an interface that is implemented using a mock framework (I think this is called Inversion of Control).

Is it safe to assume that by testing MethodA that the static method (wrapper method) is also being tested indirectly. I am assuming the actually implementation for the interface used in MethodA is also being tested.

Or should I not implemented the static method?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

浅笑依然 2024-12-19 07:23:57

请不要这样做!

像您想要的那样使用静态方法与控制反转/依赖注入完全相反,因此是一种不好的做法。
您想要做的是将接口注入到所有需要 MyClass 的类中(通过构造函数或 setter 手动注入或使用 Spring 等 IoC 框架注入)。

如果您将代码行包装在从另一个类调用的静态方法中,那么您就会将 MyClass 的特定实现耦合得太紧密,这与您想要实现的目标相反。

但要回答您更具体的问题,假设代码已通过其他测试进行测试是绝对不安全的,除非确实如此。我的意思是:如果没有通过静态方法的测试,那么它就不会被覆盖。即使您可能认为它很微不足道,也不要忘记它稍后可能会被重构,并且没有测试表明它已损坏。

Please, don't do that!

Static methods used like you want to do are the exact opposite of inversion of control / dependency injection, and as such, are a bad practice.
What you want to do is inject into all classes that need a MyClass an interface to it (either injected through the constructor or a setter, manually or using a IoC framework like Spring).

If you wrap your lines of code in a static method that you call from another class, then you'll couple the specific implementation of MyClass too tightly, which is the opposite of what you want to achieve.

But to answer your more specific question, it's never safe to assume the code is tested by another test, unless it actually is. What I mean is: if there is NO test that go through the static method, then it's not covered. Even if you may think it's trivial, don't forget it may be refactored later, and no test will indicate it's broken.

神回复 2024-12-19 07:23:57

不,假设包装器方法也正在被测试是不安全的。包装器方法中有代码,并且该代码可能存在缺陷,因此您还需要针对该代码编写单元测试。

No, it's not safe to assume the wrapper method is also being tested. There is code in the wrapper method, and that code could have a defect in it, so you'll need to write unit tests against that code as well.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文