如何使用反射访问 JUnit 中的私有 Map?
我有一个连接器类(SVNConnector),应该进行junit测试。有一个名为 private Map
应该在 JUnit 中访问,但该映射没有 getter 方法。所以我必须使用反射来做到这一点。我的问题是:这是如何运作的?我尝试了以下操作:
@BeforeClass
public static void setUpBeforeClass() throws Exception {
svnConnector = new SVNConnector(user, pwd);
Field connectionMapField = SVNConnector.class.getDeclaredField("connectionMap");
connectionMapField.setAccessible(true);
//AND NOW?
}
没有任何 Collection 特定的 getter 或 setter 来检查 collectionMap 或类似的大小。那么我怎样才能访问它呢?
谢谢。
I have a connector class (SVNConnector) which should be junit tested. There is a private map called private Map<String, SVNRepository> connectionMap
which should be accessed in JUnit, but this map doesn't have a getter method. So I have to use reflections to do that. My question is: How does that work? I tried the following:
@BeforeClass
public static void setUpBeforeClass() throws Exception {
svnConnector = new SVNConnector(user, pwd);
Field connectionMapField = SVNConnector.class.getDeclaredField("connectionMap");
connectionMapField.setAccessible(true);
//AND NOW?
}
There are not any Collection specific getters or setters to check the size of the collectionMap or similar. So how can I access it?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
你的意思是你想要获取该字段的值吗?
Do you mean you want to get the value of the field?
查看 JUnit 插件。
特别是 - http://junit-addons.sourceforge.net/junitx/util/PrivateAccessor .html
主页在这里 - http://junit-addons.sourceforge.net/
例如:
Check out JUnit-addons.
Particularly - http://junit-addons.sourceforge.net/junitx/util/PrivateAccessor.html
With the main page here - http://junit-addons.sourceforge.net/
For example:
从字段获取引用(通过使用 Field.get(Object) 方法),将其转换为 Map,然后使用它。
您可能还应该看看 Java 反射教程。
Obtain the reference form the field (by using the Field.get(Object) method), cast it to Map and then use it.
You may also should have a look at the Java Reflection Tutorial.
如果您喜欢使用其他库(和注释处理器),您可以使用 dp4j 的
@TestPrivate
s 注解:您还可以使用
-Averbose
选项查看生成的Reflection代码,复制粘贴它,然后删除@TestPrivates
Had you liked to use additional libraries (and annotation processors) you could have used dp4j's
@TestPrivate
s annotation:You can also use the
-Averbose
option to see the generated Reflection code, copy-paste it, and then remove@TestPrivates