|
1 |
| package com.agical.rmock.core.find.match.method; |
|
2 |
| |
|
3 |
| import java.lang.reflect.InvocationTargetException; |
|
4 |
| import java.lang.reflect.Method; |
|
5 |
| |
|
6 |
| import com.agical.rmock.core.exception.UnexpectedFatalSystemException; |
|
7 |
| import com.agical.rmock.core.find.MatchAction; |
|
8 |
| import com.agical.rmock.core.util.DefaultValueProvider; |
|
9 |
| |
|
10 |
| public class ExecuteMethodOnTargetMatchAction implements MatchAction, ParameterBuilder { |
|
11 |
| |
|
12 |
| private final Object target; |
|
13 |
| private final DefaultValueProvider defaultValueProvider = new DefaultValueProvider(); |
|
14 |
| |
|
15 |
| private Modifier modifier; |
|
16 |
| private ParameterProvider parameterValueProvider = new ParameterProvider() { |
|
17 |
104
| public Object getValueFor(Class clazz) {
|
|
18 |
104
| return defaultValueProvider.getDefaultValue(clazz);
|
|
19 |
| } |
|
20 |
| }; |
|
21 |
| |
|
22 |
7
| public ExecuteMethodOnTargetMatchAction(Object target) {
|
|
23 |
7
| this.target = target;
|
|
24 |
| } |
|
25 |
| |
|
26 |
63
| public void matched(Object matchedObject) {
|
|
27 |
63
| Method method = (Method)matchedObject;
|
|
28 |
63
| try {
|
|
29 |
63
| method.invoke(target, getDefaultArguments(method.getParameterTypes()));
|
|
30 |
63
| if (modifier != null) {
|
|
31 |
1
| modifier.modify();
|
|
32 |
| } |
|
33 |
| } catch (IllegalAccessException e) { |
|
34 |
0
| throw new UnexpectedFatalSystemException(e);
|
|
35 |
| } catch (InvocationTargetException e) { |
|
36 |
0
| if (e.getTargetException() instanceof RuntimeException) {
|
|
37 |
0
| throw (RuntimeException)e.getTargetException();
|
|
38 |
| } |
|
39 |
0
| else if (e.getTargetException() instanceof Error) {
|
|
40 |
0
| throw (Error)e.getTargetException();
|
|
41 |
| } |
|
42 |
| else { |
|
43 |
0
| throw new UnexpectedFatalSystemException(e);
|
|
44 |
| } |
|
45 |
| } |
|
46 |
| } |
|
47 |
| |
|
48 |
63
| private Object[] getDefaultArguments(Class[] parameterTypes) {
|
|
49 |
63
| Object[] defaultValues = new Object[parameterTypes.length];
|
|
50 |
63
| for (int i = 0; i < parameterTypes.length; i++) {
|
|
51 |
105
| defaultValues[i] = parameterValueProvider.getValueFor(parameterTypes[i]);
|
|
52 |
| } |
|
53 |
63
| return defaultValues;
|
|
54 |
| } |
|
55 |
| |
|
56 |
1
| public MatchAction modifyWith(Modifier modifier) {
|
|
57 |
1
| this.modifier = modifier;
|
|
58 |
1
| return this;
|
|
59 |
| } |
|
60 |
| |
|
61 |
1
| public ModifierBuilder withParametersFrom(ParameterProvider parameterValueProvider) {
|
|
62 |
1
| this.parameterValueProvider = parameterValueProvider;
|
|
63 |
1
| return this;
|
|
64 |
| }; |
|
65 |
| } |