私有/受保护方法是否应该进行单元测试? [英] Should Private/Protected methods be under unit test?

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

问题描述

在 TDD 开发中,您通常做的第一件事是创建接口,然后开始针对该接口编写单元测试.随着 TDD 过程的进展,您最终会创建一个实现接口的类,然后在某个时候您的单元测试将通过.

In TDD development, the first thing you typically do is to create your interface and then begin writing your unit tests against that interface. As you progress through the TDD process you would end-up creating a class that implements the interface and then at some point your unit test would pass.

现在我的问题是关于我可能必须在我的类中编写的私有和受保护方法以支持接口公开的方法/属性:

Now my question is about the private and protected methods that I might have to write in my class in support of the methods/properties exposed by the interface:

  • 类中的私有方法是否应该有自己的单元测试?

  • Should the private methods in the class have their own unit tests?

类中受保护的方法是否应该有自己的单元测试?

Should the protected methods in the class have their own unit tests?

我的想法:

  • 特别是因为我正在对接口进行编码,所以我不应该担心受保护/私有方法,因为它们是黑匣子.

  • Especially because I am coding to interfaces, I shouldn't worry about protected/private methods as they are black boxes.

因为我在使用接口,所以我正在编写单元测试来验证定义的契约是否由实现接口的不同类正确实现,所以我不应该担心私有/受保护的方法,它们应该被执行通过调用接口定义的方法/属性的单元测试.

Because I am using interfaces, I am writing unit tests to validate that the contract defined is properly implemented by the different classes implementing the interface, so again I shouldnt worry about the private/protected methods and they should be exercised via unit tests that call the methods/properties defined by the interface.

如果我的代码覆盖率没有显示受保护/私有方法被命中,那么我没有正确的单元测试,或者我的代码没有被使用并且应该被删除.

If my code-coverage does not show that the protected/private methods are being hit, then I don't have the right unit-tests or I have code thats not being used and should be removed.

推荐答案

不,我不考虑测试私有或受保护的方法.类的私有和受保护方法不是公共接口的一部分,因此它们不公开公共行为.通常,这些方法是由您在使测试变为绿色后应用的重构创建的.

No, I don't think of testing private or protected methods. The private and protected methods of a class aren't part of the public interface, so they don't expose public behavior. Generally these methods are created by refactorings you apply after you've made your test turn green.

因此,这些私有方法由断言公共接口行为的测试隐式测试.

So these private methods are tested implicitly by the tests that assert the behavior of your public interface.

从更哲学的角度来说,请记住您是在测试行为,而不是方法.因此,如果您考虑被测类可以做的那组事情,只要您可以测试并断言该类的行为是否符合预期,是否有该类内部使用的私有(和受保护)方法来实现这种行为无关紧要.这些方法是公共行为的实现细节.

On a more philosophical note, remember that you're testing behavior, not methods. So if you think of the set of things that the class under test can do, as long as you can test and assert that the class behaves as expected, whether there are private (and protected) methods that are used internally by the class to implement that behavior is irrelevant. Those methods are implementation details of the public behavior.

这篇关于私有/受保护方法是否应该进行单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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