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 394a7b9

Browse filesBrowse files
committed
优化“如何测试 private 方法,变量或者内部类”并添加到首页
1 parent 9480644 commit 394a7b9
Copy full SHA for 394a7b9

File tree

Expand file treeCollapse file tree

2 files changed

+8
-3
lines changed
Filter options
Expand file treeCollapse file tree

2 files changed

+8
-3
lines changed

‎README.md

Copy file name to clipboardExpand all lines: README.md
+2Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,8 @@ stackoverflow-Java-top-qa
4646
* [StringBuilder和StringBuffer有哪些区别呢](https://github.com/giantray/stackoverflow-java-top-qa/blob/master/contents/stringbuilder-and-stringbuffer.md)
4747
* [为什么处理排序的数组要比非排序的快](https://github.com/giantray/stackoverflow-java-top-qa/blob/master/contents/Why-is-processing-a-sorted-array-faster-than-an-unsorted-array.md)
4848

49+
> 测试
50+
* [如何测试 private 方法,变量或者内部类](https://github.com/giantray/stackoverflow-java-top-qa/blob/master/contents/How_to_test_a_class_that_has_private_methods,_fields_or_inner_classes.md)
4951

5052
### 待翻译问题链接(还剩x问题)
5153
- [Why is subtracting these two times (in 1927) giving a strange result?](http://stackoverflow.com/questions/6841333/why-is-subtracting-these-two-times-in-1927-giving-a-strange-result)

‎contents/How_to_test_a_class_that_has_private_methods,_fields_or_inner_classes.md

Copy file name to clipboardExpand all lines: contents/How_to_test_a_class_that_has_private_methods,_fields_or_inner_classes.md
+6-3Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
1-
# 如何使用 junit 测试 private 方法,变量或者内部类
1+
# 如何测试 private 方法,变量或者内部类
22

3-
当你需要测试一个遗留的应用程序,且不能更改方法的可见性时,那测试私有方法/属性的最好方式就是使用[反射](https://en.wikipedia.org/wiki/Reflection_%28computer_programming%29)
3+
当你需要测试一个遗留的应用程序,且不能更改方法的可见性时,那么,测试私有方法/属性的最好方式就是使用[反射](https://en.wikipedia.org/wiki/Reflection_%28computer_programming%29)
44

5-
实际测试时,可以通过一些反射辅助类设置和获取私有(静态)的变量和调用私有(静态)方法。遵循下面的窍门,你可以很好地处理私有方法和变量的测试。
5+
实际测试时,可以通过一些反射辅助类,设置和获取私有(静态)的变量、调用私有(静态)方法。遵循下面的窍门,你可以很好地处理私有方法和变量的测试。
66

77
```
88
Method method = targetClass.getDeclaredMethod(methodName, argClasses);
@@ -18,5 +18,8 @@ field.setAccessible(true);
1818
field.set(object, value);
1919
2020
```
21+
> note:
22+
> 1. `targetClass.getDeclaredMethod(methodName, argClasses)`这个方法能让你获取到私有方法。`getDeclaredField`让你获取到私有变量
23+
> 2. 在对私有变量(方法)进行处理前,需要先`setAccessible(true)`
2124
2225
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.