我应该是访问的单元测试protected的方法? [英] Should I be accessing protected methods for unit tests?

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

问题描述

在关于这个问题我刚才问的,我用我的单元测试再次卡住了。

In relation to this question I asked earlier, I am stuck yet again with my unit test.

我现在的问题是,相对于测试保护我的抽象方法组件类。

My current problem is in relation to testing the protected methods of my abstract Component class.

我已经成功地实现了一个模拟类,命名为 ConcreteComponent ,其中它的工作非常好继承一切抽象类有。

I've successfully implemented a mock class, named ConcreteComponent, which does its job very well of inheriting everything the abstract class has.

事情是,我做我的单元测试文件,这里面具体类。测试方法保护的唯一方法是有一个私人的存取。但是,我不能创建相同的文件所在的单元测试是内部的专用访问器,因此无法访问受保护的方法。

Thing is, I made this concrete class inside my unit test file. The only way of testing protected methods is to have a Private Accessor. However, I cannot create a Private Accessor inside the same file as where the unit test is, and thus, cannot access the protected methods.

我试着放置在一个单独的文件模拟具体类,在不同的命名空间,而这现在让我来创建一个私人的存取到单元测试文件,现在可以使用。它的工作很好,但我想我需要在那里的单元测试是在同一个文件内这个模拟具体类

I've tried to place the mock concrete class in a separate file, under a different namespace, and this now allows me to create a Private Accessor to which the unit test file can now use. It worked nicely, but then I figured I need this mock concrete class inside the same file where the unit test is.

所以,现在我有两个问题:

So now I have two questions:

1)什么是这个问题的可能的解决方法?

1) What are the possible workarounds for this problem?

2)为什么我不能创建一个私有访问模拟类,这是相同的文件和命名空间为单元测试类里面呢?

2) Why can't I create a private accessor for a mock class which is inside the same file and namespace as the unit test class?

推荐答案

您可以看看的 PrivateObject 类能够在测试中访问类的非公开的API。它使用反射内部。一类的保护的资产仍API到外部客户端在这种情况下是一个子或派生的类。所以,希望来测试这种API是可以理解的。我不会推荐污染类暴露公共API只是为了测试保护API的缘故。然而,因为在你的情况下,派生类在测试项目中,你实际上可以提供公共的API使测试更加简单,提高了性能(反射会慢一些,如果你正在运行测试,连续测试,当你更改代码,它可能使测试运行速度较慢取决于测试等)的数量。

You can take a look at PrivateObject class to gain access to non-public API of your class in your tests. It uses reflection internally. Protected assets of a class are still api to an external client which in this case is a sub or derived class. So desire to test such api is understandable. I would not recommend polluting a class to expose public api just for the sake of testing protected api. However, since in your case the derived class is in a test project, you can actually provide public api to make testing easier and improve the performance (reflection will be slower and if you are running tests, continuous testing, as you make code changes, it may make test runs slower depending on the number of test etc.).

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

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