对私有方法的单元测试问题 [英] Questions on unit testing of private methods

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

问题描述

在MSTest的,在 [阴影] 属性可以帮助您进行单元测试从另一个程序集的私有方法。以下是相关链接:<一href="http://stackoverflow.com/questions/3443755/what-is-the-shadowing-attribute-that-the-vs-uses-when-it-generates-unit-tests">What是的阴影属性的VS时,它产生的单元测试使用?

我的问题是:

  1. 如果私有方法单位单独测试?
  2. 这是个好(?)的做法,以改变私有方法的访问,以内部只是为了使其可用于单元测试其他一些测试项目/组件? (使用 InternalsVisibleTo
  3. 如果私有方法获得通过调用它们的公共方法间接地测试,可以在被称为单位测试?
解决方案
  1. 无,私有方法不应该被测试。您的应用程序将与唯一的公共API交互。所以,你应该为这个互动测试类的预期行为。私有方法是内在的逻辑实现的一部分。类的用户应该不会关心它是如何实现的。
  2. 不,这是不好的。往上看。您应该仅测试公共API。
  3. 您应该测试唯一的公共方法。你不介意的公共方法调用私有方法或将直到测试通过。如果测试失败,修复实现。但不要反正测试私有方法。

更新(如何定义测试什么): 理想的情况下(在测试先行的方法)测试类的第一个用户。当你写测试,你试着想象用户如何使用你的类。用户将不能与私有方法交互(反射是一种欺骗行为)。所以,你的考验,因为你的类的第一个用户,不应与私有方法进行交互。

In MSTest, the [Shadowing] attribute helps you to unit test a private method from another assembly. Here is the related link : What is the Shadowing attribute that the VS uses when it generates unit tests?

My questions are:

  1. Should private methods be unit tested separately?
  2. Is it a good (?) practice to change private method's accessor to internal just to make it available for unit testing in some other test project/assembly? (using InternalsVisibleTo)
  3. If private methods get tested indirectly through the public method that calls them, can it be called "unit" testing?

解决方案

  1. No, private methods should not be tested. Your application will interact with public API only. So you should test expected behavior of your class for this interaction. Private methods is a part of inner logic implementation. Users of your class should not be care how it implemented.
  2. No, it is not good. See above. You should test public API only.
  3. You should test only public methods. You don't care if public method will call to private method or will not until test is passed. If test fails, fix implemetation. But don't test private methods anyway.

UPDATE (how to define what to test): Ideally (in test-first approach) test is the first user of your class. When you write test, you try to imagine how users will use your class. Users will not interact with private methods (Reflection is cheating). So and your test, as first user of your class, should not interact with private methods.

这篇关于对私有方法的单元测试问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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