Skip to content

Commit 58260dc

Browse files
committed
Merge pull request giantray#6 from peiquan/master
如何测试 private 方法,变量或者内部类
2 parents d24c560 + 57d785f commit 58260dc

File tree

2 files changed

+74
-0
lines changed

2 files changed

+74
-0
lines changed
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
# 如何测试一个数组是否包含指定的值
2+
3+
指定数组,如:
4+
```
5+
public static final String[] VALUES = new String[] {"AB","BC","CD","AE"};
6+
```
7+
现在制定一个值 s,有哪些比较好的方式,判断这个数组 VALUES 是否包含值 s?
8+
9+
简单且优雅的方法:
10+
```
11+
Arrays.asList(yourArray).contains(yourValue);
12+
```
13+
14+
问题的本质,其实是一个查找的问题,即查找一个数组是否包含某个值。对于原始类型,若是无序的数组,可以直接写一个 for 循环:
15+
```
16+
public static boolean useLoop(String[] arr, String targetValue) {
17+
for(String s: arr){
18+
if(s.equals(targetValue))
19+
return true;
20+
}
21+
return false;
22+
}
23+
```
24+
若是有序的数组,可以考虑二分查找或者其他查找算法:
25+
```
26+
public static boolean useArraysBinarySearch(String[] arr, String targetValue) {
27+
int a = Arrays.binarySearch(arr, targetValue);
28+
if(a >= 0)
29+
return true;
30+
else
31+
return false;
32+
}
33+
```
34+
35+
若数组里包含的是一个个对象,实际上比较就是引用是否相等(String 类型是判断 值是否相等),本质就是比较 hashcode 和 equal 方法,可以考虑使用 List 或者 Set,如下
36+
```
37+
public static boolean useList(String[] arr, String targetValue) {
38+
return Arrays.asList(arr).contains(targetValue);
39+
}
40+
```
41+
42+
```
43+
public static boolean useLoop(String[] arr, String targetValue) {
44+
for(String s: arr){
45+
if(s.equals(targetValue))
46+
return true;
47+
}
48+
return false;
49+
}
50+
```
51+
52+
stackoverflow原址:http://stackoverflow.com/questions/1128723/how-can-i-test-if-an-array-contains-a-certain-value
Lines 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)