C#"内部"在做单元测试的时候访问修饰符 [英] C# "internal" access modifier when doing unit testing

查看:141
本文介绍了C#"内部"在做单元测试的时候访问修饰符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在单元测试中新,我试图找出我是否应该开始使用更多的内部访问修饰符。我知道,如果我们使用内部,并设置装配变量InternalsVisibleTo',我们可以测试,我们不希望从测试项目申报的公共职能。这让我觉得,我应该只是一直使用'内部',因为至少每个项目(应注意什么?)有它自己的测试项目。你们能告诉我为什么我不应该这样做呢?什么时候应该使用'私有'?

I'm new in unit testing and I'm trying to figure out if I should start using more of 'internal' access modifier. I know that if we use 'internal' and set the assembly variable 'InternalsVisibleTo', we can test functions that we don't want to declare public from the testing project. This makes me think that I should just always use 'internal' because at least each project (should?) has it's own testing project. Can you guys tell me a reason why I shouldn't do this? When should I use 'private'?

推荐答案

在理论上你只需要应该反正测试你的公共方法。只要有足够的测试,你正在测试的所有code路径。在现实中,你可能要验证的东西按预期工作称之为问心无愧了一大堆更多code之前。

In theory you should only need to test your public methods anyway. Just have enough tests that you are testing all the code paths. In reality you may want to verify something works as expected before calling it wth a whole lot more code.

如果您使用的是TDD(测试驱动开发)这通常不是一个问题,没有code,而不测试书面所以没有code路径应保持未经检验。内部,保护,再私有方法产卵,你对重构现有的测试。

If you are using TDD (Test Driven Development) this is not usually an issue as no code is written without a test so no code path should remain untested. Internal, protected and private methods are then spawned as you refactor against your existing tests.

问题,当你不使用TDD,并有适合的测试为已写入code来。那么你可能想测试单个方法,而没有让他们公开。

The problem comes when you aren't using TDD and have to fit tests into already written code. Then you might want to test individual methods without making them public.

有方法和途径,你可以做到这一点。 VS2008提供了一个辅助生成,你可以用它来测试内部方法内部访问。或者,您可以通过使用受保护的(不是私人的方法)和继承滚你自己的。

There are ways and means you can do that. VS2008 offers a helper to generate internal accessors which you can use to test internal methods. Or you can roll your own by using protected (not private methods) and inheritance.

这篇关于C#"内部"在做单元测试的时候访问修饰符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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