1 // ****************************************************************
2 // Copyright 2007, Charlie Poole
3 // This is free software licensed under the NUnit license. You may
4 // obtain a copy of the license at http://nunit.org/?p=license&r=2.4
5 // ****************************************************************
8 using System
.Collections
;
9 using System
.Runtime
.Remoting
.Proxies
;
10 using System
.Runtime
.Remoting
.Messaging
;
11 using NUnit
.Framework
;
16 /// Summary description for MockObject.
18 public class Mock
: IMock
20 #region Private Fields
26 private IDictionary methods
= new Hashtable();
28 private Exception lastException
;
34 public Exception LastException
36 get { return lastException; }
43 public Mock() : this( "Mock" ) { }
45 public Mock( string name
)
61 get { return strict; }
62 set { strict = value; }
65 public void Expect( string methodName
, params object[] args
)
67 ExpectAndReturn( methodName
, null, args
);
70 public void Expect( string methodName
)
72 ExpectAndReturn( methodName
, null, null );
75 public void ExpectNoCall( string methodName
)
77 methods
[methodName
] = new MockMethod( methodName
, null,
78 new AssertionException("Unexpected call to method " + methodName
) );
81 public void ExpectAndReturn( string methodName
, object returnVal
, params object[] args
)
83 AddExpectedCall( methodName
, returnVal
, null, args
);
86 public void ExpectAndThrow( string methodName
, Exception exception
, params object[] args
)
88 AddExpectedCall( methodName
, null, exception
, args
);
91 public void SetReturnValue( string methodName
, object returnVal
)
93 methods
[methodName
] = new MockMethod( methodName
, returnVal
);
98 #region IVerify Members
100 public virtual void Verify()
102 foreach( IMethod method
in methods
.Values
)
108 #region ICallHandler Members
110 public virtual object Call( string methodName
, params object[] args
)
112 if ( methods
.Contains( methodName
) )
116 IMethod method
= (IMethod
)methods
[methodName
];
117 return method
.Call( args
);
119 catch( Exception exception
)
121 // Save exception in case MO is running on a separate thread
122 lastException
= exception
;
126 else // methodName is not listed in methods
128 Assert
.Fail( "Unexpected call to " + methodName
);
130 // not listed but Strict is not specified
136 #region Helper Methods
138 private void AddExpectedCall( string methodName
, object returnVal
, Exception exception
, object[] args
)
140 IMethod method
= (IMethod
)methods
[methodName
];
141 if ( method
== null )
143 method
= new MockMethod( methodName
);
144 methods
[methodName
] = method
;
147 Type
[] argTypes
= MethodSignature
.GetArgTypes( args
);
148 MethodSignature signature
= new MethodSignature( this.Name
, methodName
, argTypes
);
150 method
.Expect( new MockCall( signature
, returnVal
, exception
, args
) );