KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > codehaus > dna > impl > MockInvocationRecorder


1 /*
2  * Copyright (C) The DNA Group. All rights reserved.
3  *
4  * This software is published under the terms of the DNA
5  * Software License version 1.1, a copy of which has been included
6  * with this distribution in the LICENSE.txt file.
7  */

8 package org.codehaus.dna.impl;
9
10 import java.lang.reflect.InvocationHandler JavaDoc;
11 import java.lang.reflect.Method JavaDoc;
12 import java.util.ArrayList JavaDoc;
13 import java.util.Arrays JavaDoc;
14 import java.util.List JavaDoc;
15 import junit.framework.Assert;
16
17 class MockInvocationRecorder
18     implements InvocationHandler JavaDoc
19 {
20     private List JavaDoc m_invocations = new ArrayList JavaDoc();
21     private int m_index;
22
23     public void addInvocation( final Method JavaDoc method,
24                                final Object JavaDoc[] args,
25                                final Object JavaDoc result )
26     {
27         final InvocationRecord record = new InvocationRecord();
28         record.m_method = method;
29         record.m_args = args;
30         record.m_result = result;
31         m_invocations.add( record );
32     }
33
34     public Object JavaDoc invoke( final Object JavaDoc proxy,
35                           final Method JavaDoc method,
36                           final Object JavaDoc[] args )
37         throws Throwable JavaDoc
38     {
39         InvocationRecord record = (InvocationRecord)m_invocations.get( m_index++ );
40         if( null == record )
41         {
42             Assert.fail( "Unexpected invocation " + method.getName() + " with args " + Arrays.asList( args ) +
43                          " at index " + m_index + " when expecting " + m_invocations.size() + "invocations" );
44         }
45         Assert.assertEquals( "method", record.m_method, method );
46         if( args != null && record.m_args != null )
47         {
48             Assert.assertEquals( "args.length", record.m_args.length, args.length );
49         }
50         else if( args == null && 0 != record.m_args.length )
51         {
52             Assert.fail( "Got empty args but expected " + Arrays.asList( record.m_args ) );
53         }
54         else if( record.m_args == null && 0 != args.length )
55         {
56             Assert.fail( "Expected empty args but got " + Arrays.asList( args ) );
57         }
58
59         return record.m_result;
60     }
61 }
62
Popular Tags