Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit 2d17709

Browse filesBrowse files
author
zhupeiquan
committed
How_to_test_a_class_that_has_private_methods,_fields_or_inner_classes
1 parent ce97a7c commit 2d17709
Copy full SHA for 2d17709

File tree

Expand file treeCollapse file tree

1 file changed

+22
-0
lines changed
Filter options
Expand file treeCollapse file tree

1 file changed

+22
-0
lines changed
+22Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
# 如何使用 junit 测试 private 方法,变量或者内部类
2+
3+
当你需要测试一个遗留的应用程序,且不能更改方法的可见性时,测试私有方法/属性的最好方式就是使用[反射](https://en.wikipedia.org/wiki/Reflection_%28computer_programming%29)
4+
5+
实际测试时,可以通过一些反射辅助类设置和获取私有(静态)的变量和调用私有(静态)方法。遵循下面的窍门,你可以很好地处理私有方法和变量的测试。
6+
7+
```
8+
Method method = targetClass.getDeclaredMethod(methodName, argClasses);
9+
method.setAccessible(true);
10+
return method.invoke(targetObject, argObjects);
11+
```
12+
13+
私有变量:
14+
15+
```
16+
Field field = targetClass.getDeclaredField(fieldName);
17+
field.setAccessible(true);
18+
field.set(object, value);
19+
20+
```
21+
22+
stackoverflow原址:http://stackoverflow.com/questions/34571/how-to-test-a-class-that-has-private-methods-fields-or-inner-classes

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.