Learning MockUp ( : the API MockUp time), MockUp custom methods can body, the method that covers the original. JMockit provides us with a special method for intercepting all the way for us to do AOP approach is based on Mock. For example, we want to test time performance of each method.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
//通过在mock时做AOP测试方法的时间性能
public
class
MethodCostPerformanceTest {
// 测试SayHello类每个方法的时间性能
@Test
public
void
testSayHelloCostPerformance() {
// 把方法的调用时间记录到costMap中。key是方法名称,value是平均调用时间
Map<String, Long> costMap =
new
HashMap<String, Long>();
new
MockUp<SayHello>() {
@Mock
public
Object $advice(Invocation invocation) {
long
a = System.currentTimeMillis();
Object result = invocation.proceed();
long
cost = System.currentTimeMillis() - a;
// 把某方法的平均调用时间记录下来
String methodName = invocation.getInvokedMember().getName();
Long preCost = costMap.get(methodName);
if
(preCost ==
null
) {
costMap.put(methodName, cost);
}
else
{
costMap.put(methodName, (preCost + cost) /
2
);
}
return
result;
}
};
SayHello sayHello =
new
SayHello();
sayHello.sayHello(
"david"
, ISayHello.MALE);
sayHello.sayHello(
"lucy"
, ISayHello.FEMALE);
for
(Iterator<String> iterator = costMap.keySet().iterator(); iterator.hasNext();) {
String methodName = (String) iterator.next();
// 期望每个方法的调用时间不超过20ms
Assert.isTrue(costMap.get(methodName) <
20
);
}
}
}
|