Example #1
0
        /// <summary>
        /// Creates a mocked instance for the given serverType.
        /// </summary>
        /// <param name="serverType">The type for which to create an instance.
        /// Should be the type decorated by this attribute.</param>
        protected virtual MarshalByRefObject CreateMockedInstance(Type serverType)
        {
            IMocker customMocker;

            // Retrieve customMockerType from name:
            if (this.customMockerType == null)
            {
                this.customMockerType = Type.GetType(customMockerTypeName);
            }
            // Check customMockerType exists:
            if (this.customMockerType == null)
            {
                throw new TypeLoadException(String.Format("The typename \"{0}\" configured as mocker on a CustomMockAttribute could not be resolved.", this.customMockerTypeName));
            }
            // Create custom mocker:
            customMocker = (IMocker)customMockerType.GetConstructor(new Type[] {}).Invoke(new object[] {});
            // Create proxy, return transparent proxy:
            RealProxy rp;

            if (RecorderManager.IsRecording)
            {
                rp = new MockingProxy(serverType, customMocker, RecorderManager.GetNextInstanceName(serverType));
            }
            else
            {
                rp = new MockingProxy(serverType, customMocker, null);
            }
            return((MarshalByRefObject)rp.GetTransparentProxy());
        }
Example #2
0
 public void HandleCall(MockingProxy proxy, MockableCall call)
 {
     using (new RecorderManager.Lock()) {
         call.SetResult(InvokeOnServer(proxy, call));
         RecorderManager.RecordCall(call);
     }
 }
        /// <summary>
        /// Receiving an array of values, it returns an array of the same values where
        /// mockers are replaced by null (substitutedValues), and an array of substitutions
        /// indicating the positions, typenames and instancenames of the mockers (substitutions).
        /// </summary>
        /// <param name="values">The original values.</param>
        /// <param name="substitutedValues">The substituted values (original values or null for mockers).</param>
        /// <param name="substitutions">Position, type and name information of mockers.</param>
        private static void SubstituteMockers(object[] values, out object[] substitutedValues, out object[] substitutions)
        {
            ArrayList substitutionsTemp = new ArrayList();

            substitutedValues = new object[values.Length];
            for (int i = 0; i < values.Length; i++)
            {
                if (values[i] == null)
                {
                    substitutedValues[i] = null;
                }
                else if (RemotingServices.IsTransparentProxy(values[i]))
                {
                    substitutedValues[i] = null;
                    MockingProxy rp = RemotingServices.GetRealProxy(values[i]) as MockingProxy;
                    substitutionsTemp.Add(new object[] { i, TypeRef(rp.ServerType), rp.InstanceName });
                }
                else if (values[i].GetType().IsSerializable)
                {
                    substitutedValues[i] = values[i];
                }
                else
                {
                    substitutedValues[i] = null;
                }
            }
            substitutions = substitutionsTemp.ToArray();
        }
 /// <summary>
 /// Instantiates a new MockableCall object based on a MethodBase.
 /// </summary>
 /// <param name="callee">The proxy of the called object.</param>
 /// <param name="method">The method of this call.</param>
 /// <param name="arguments">The arguments passed to the methodcall (output arguments must be provided but they can have any value).</param>
 public MockableCall(MockingProxy callee, System.Reflection.MethodBase method, object[] arguments)
 {
     if (callee == null)
     {
         throw new ArgumentNullException("callee");
     }
     if (method == null)
     {
         throw new ArgumentNullException("method");
     }
     this.originalCall     = null;
     this.callCreationTime = Environment.TickCount;
     this.callee           = callee;
     this.method           = method;
     this.inArgs           = new object[this.GetInParameters().Length];
     if (arguments != null)
     {
         int i = 0;
         foreach (ParameterInfo param in this.GetInParameters())
         {
             this.inArgs[i++] = arguments[param.Position];
         }
     }
     this.isConstructorCall = (method.IsConstructor);
     this.isCompleted       = false;
 }
		private IMethodReturnMessage InvokeOnServer(MockingProxy proxy, MockableCall call) {
			IMessage request = call.OriginalCall;
			IMethodCallMessage mcm = request as IMethodCallMessage;
			IConstructionCallMessage ccm = request as IConstructionCallMessage;
			if(ccm != null) {
				try {
					// Attach server instance:
					//   (we do it only for MarshalByRefObjects as it's a requirement, don't really
					//    know however what's the added value of attachingToServer... it also works
					//    well without doing this)
					if (this.serverInstance is MarshalByRefObject) proxy.AttachServer((MarshalByRefObject)this.serverInstance);
					// Call instance constructor:
					RemotingServices.GetRealProxy(serverInstance).InitializeServerObject(ccm);
					// Build response:
					return MockingTools.BuildReturnMessage(proxy.GetTransparentProxy(), ccm.Args, mcm);
				} catch (Exception ex) {
					// Build response:
					return MockingTools.BuildReturnMessage(ex, mcm);
				}
			} else {
				try {
					// Invoke instance method:
					object[] args = new object[mcm.ArgCount];
					mcm.Args.CopyTo(args, 0);
					object result = mcm.MethodBase.Invoke(serverInstance, args);
					// Build response:
					return MockingTools.BuildReturnMessage(result, args, mcm);
				} catch (TargetInvocationException ex) {
					// Build response:
					return MockingTools.BuildReturnMessage(ex.InnerException, mcm);
				}
			}
		}
		public void Serialization01Test()
		{
			MemoryStream buffer = new MemoryStream();
			IFormatter formatter = new global::System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();

			// Create some call:
			ArrayList result = new ArrayList();
			result.Add("One");
			result.Add("Two");
			MockingProxy callee = new MockingProxy(typeof(Sample.FooBar), null, "m1");
			MockableCall call = new MockableCall(callee, typeof(Sample.FooBar).GetMethod("SomeMethodWithInsAndOuts"), new object[] { 1, 2, null, 3 });
			call.SetCallResult(result, new object[] { 7, 13 });

			// Serialize it:
			formatter.Serialize(buffer, call);
			buffer.Flush();

			// Deserialize it:
			buffer.Position = 0;
			MockableCall deserializedCall = (MockableCall)formatter.Deserialize(buffer);

			// Test result:
			Assert.IsNotNull(deserializedCall);
			Assert.IsFalse(deserializedCall.IsConstructorCall);
			Assert.IsNotNull(deserializedCall.Method);
			Assert.AreEqual("SomeMethodWithInsAndOuts", deserializedCall.Method.Name);
			Assert.AreEqual("Two", ((ArrayList)deserializedCall.ReturnValue)[1]);
			Assert.AreEqual(3, deserializedCall.InArgs[2]);
			Assert.AreEqual(13, deserializedCall.OutArgs[1]);
			Assert.IsTrue(deserializedCall.IsCompleted);
		}
Example #7
0
		/// <summary>
		/// Instantiates a new MockableCall object based on a IMethodCallMessage.
		/// </summary>
		public MockableCall(MockingProxy callee, IMethodCallMessage callmsg) {
			if (callee == null) throw new ArgumentNullException("callee");
			if (callmsg == null) throw new ArgumentNullException("callmsg");
			this.originalCall = callmsg;
			this.callCreationTime = Environment.TickCount;
			this.callee = callee;
			this.method = callmsg.MethodBase;
			this.inArgs = callmsg.InArgs;
			this.isConstructorCall = (callmsg is IConstructionCallMessage);
			this.isCompleted = false;
		}
		/// <summary>
		/// Creates and returns a mocker for the given object type.
		/// </summary>
		/// <param name="type">The object type to mock. This can be either an interface, or a type derived from MarshalByRef.</param>
		/// <param name="name">The name uniquely identifying the instance.</param>
		public virtual ManualMocker Mock(Type type, string name) {
			try {
				ManualMocker mocker = new ManualMocker();
				MockingProxy proxy = new MockingProxy(type, mocker, name);
				mocker.Initialize(proxy);
				mockers.Add(mocker);
				return mocker;
			} catch (ArgumentException ex) {
				throw new MockException("Type to mock must be an interface or derive from MarshalByRef.", ex);
			}
		}
Example #9
0
		/// <summary>
		/// Instantiates a new MockableCall object based on a MethodBase.
		/// </summary>
		/// <param name="callee">The proxy of the called object.</param>
		/// <param name="method">The method of this call.</param>
		/// <param name="arguments">The arguments passed to the methodcall (output arguments must be provided but they can have any value).</param>
		public MockableCall(MockingProxy callee, System.Reflection.MethodBase method, object[] arguments){
			if (callee == null) throw new ArgumentNullException("callee");
			if (method == null) throw new ArgumentNullException("method");
			this.originalCall = null;
			this.callCreationTime = Environment.TickCount;
			this.callee = callee;
			this.method = method;
			this.inArgs = new object[this.GetInParameters().Length];
			if (arguments != null) {
				int i = 0;
				foreach(ParameterInfo param in this.GetInParameters()) {
					this.inArgs[i++] = arguments[param.Position];
				}
			}
			this.isConstructorCall = (method.IsConstructor);
			this.isCompleted = false;
		}
		/// <summary>
		/// Creates an eventually mocked instance for the given serverType.
		/// </summary>
		/// <param name="serverType">The type for which to create an instance.
		/// Should be the type decorated by this attribute.</param>
		protected override MarshalByRefObject CreateMockedInstance(Type serverType) {
			RealProxy rp;
			switch (RecorderManager.Action) {
				case RecorderState.Recording:
					// Create a recording proxy for the object:
					MarshalByRefObject target = CreateUnmockedInstance(serverType);
					rp = new MockingProxy(serverType, new RecordingMocker(target), RecorderManager.GetNextInstanceName(serverType));
					return (MarshalByRefObject)rp.GetTransparentProxy();
				case RecorderState.PlayBack:
					// Create a playback proxy:
					rp = new MockingProxy(serverType, new PlayBackMocker(), null);
					return (MarshalByRefObject)rp.GetTransparentProxy();
				default:
					// Create an instance without proxy:
					return CreateUnmockedInstance(serverType);
			}
		}
Example #11
0
 /// <summary>
 /// Instantiates a new MockableCall object based on a IMethodCallMessage.
 /// </summary>
 public MockableCall(MockingProxy callee, IMethodCallMessage callmsg)
 {
     if (callee == null)
     {
         throw new ArgumentNullException("callee");
     }
     if (callmsg == null)
     {
         throw new ArgumentNullException("callmsg");
     }
     this.originalCall      = callmsg;
     this.callCreationTime  = Environment.TickCount;
     this.callee            = callee;
     this.method            = callmsg.MethodBase;
     this.inArgs            = callmsg.InArgs;
     this.isConstructorCall = (callmsg is IConstructionCallMessage);
     this.isCompleted       = false;
 }
Example #12
0
 /// <summary>
 /// Returns the instance name of the given mock instance.
 /// If the passed object is not a mock, null is returned.
 /// </summary>
 public static string GetInstanceName(object mock)
 {
     if (System.Runtime.Remoting.RemotingServices.IsTransparentProxy(mock))
     {
         MockingProxy proxy = System.Runtime.Remoting.RemotingServices.GetRealProxy(mock) as MockingProxy;
         if (proxy == null)
         {
             return(null);
         }
         else
         {
             return(proxy.InstanceName);
         }
     }
     else
     {
         return(null);
     }
 }
Example #13
0
        private IMethodReturnMessage InvokeOnServer(MockingProxy proxy, MockableCall call)
        {
            IMessage                 request = call.OriginalCall;
            IMethodCallMessage       mcm     = request as IMethodCallMessage;
            IConstructionCallMessage ccm     = request as IConstructionCallMessage;

            if (ccm != null)
            {
                try {
                    // Attach server instance:
                    //   (we do it only for MarshalByRefObjects as it's a requirement, don't really
                    //    know however what's the added value of attachingToServer... it also works
                    //    well without doing this)
                    if (this.serverInstance is MarshalByRefObject)
                    {
                        proxy.AttachServer((MarshalByRefObject)this.serverInstance);
                    }
                    // Call instance constructor:
                    RemotingServices.GetRealProxy(serverInstance).InitializeServerObject(ccm);
                    // Build response:
                    return(MockingTools.BuildReturnMessage(proxy.GetTransparentProxy(), ccm.Args, mcm));
                } catch (Exception ex) {
                    // Build response:
                    return(MockingTools.BuildReturnMessage(ex, mcm));
                }
            }
            else
            {
                try {
                    // Invoke instance method:
                    object[] args = new object[mcm.ArgCount];
                    mcm.Args.CopyTo(args, 0);
                    object result = mcm.MethodBase.Invoke(serverInstance, args);
                    // Build response:
                    return(MockingTools.BuildReturnMessage(result, args, mcm));
                } catch (TargetInvocationException ex) {
                    // Build response:
                    return(MockingTools.BuildReturnMessage(ex.InnerException, mcm));
                }
            }
        }
Example #14
0
        /// <summary>
        /// Creates an eventually mocked instance for the given serverType.
        /// </summary>
        /// <param name="serverType">The type for which to create an instance.
        /// Should be the type decorated by this attribute.</param>
        protected override MarshalByRefObject CreateMockedInstance(Type serverType)
        {
            RealProxy rp;

            switch (RecorderManager.Action)
            {
            case RecorderState.Recording:
                // Create a recording proxy for the object:
                MarshalByRefObject target = CreateUnmockedInstance(serverType);
                rp = new MockingProxy(serverType, new RecordingMocker(target), RecorderManager.GetNextInstanceName(serverType));
                return((MarshalByRefObject)rp.GetTransparentProxy());

            case RecorderState.PlayBack:
                // Create a playback proxy:
                rp = new MockingProxy(serverType, new PlayBackMocker(), null);
                return((MarshalByRefObject)rp.GetTransparentProxy());

            default:
                // Create an instance without proxy:
                return(CreateUnmockedInstance(serverType));
            }
        }
		public void HandleCall(MockingProxy proxy, MockableCall call)
		{
			if (call.IsConstructorCall)
			{
				call.SetConstructionResult("CurrencyMock");
			}
			else
			{
				if (call.Method.Name.Equals("ConvertAmount"))
				{
					// Retrieve call args:
					decimal amount = (decimal)call.InArgs[0];
					// Mock the call:
					call.SetCallResult(amount);
				}
				else
				{
					// Return from a void call:
					call.SetCallResult();
				}
			}
		}
		public void Serialization02Test()
		{

			// Create and initialize formatter:
			Sfmt.Binary.BinaryFormatter formatter = new Sfmt.Binary.BinaryFormatter();
			formatter.AssemblyFormat = Sfmt.FormatterAssemblyStyle.Simple;

			// Create DS:
			global::System.Data.DataSet ds = new global::System.Data.DataSet();
			global::System.Data.DataTable dt = ds.Tables.Add("SomeTable");
			global::System.Data.DataColumn dc1 = dt.Columns.Add("ID", typeof(global::System.Int32));
			ds.AcceptChanges();

			// Create MockableCall:
			MockingProxy callee = new MockingProxy(typeof(Sample.FooBar), null, "m1");
			MockableCall call = new MockableCall(callee, typeof(Sample.FooBar).GetMethod("SomeMethodWithInsAndOuts"), new object[] { 1, 2, null, 3 });

			// Set dataset as callresult:
			call.SetCallResult(ds);

			Assert.IsNotNull(call.ReturnValue, "Test setup failure, test could not even be run !");

			// Serialize call:
			MemoryStream buffer = new MemoryStream();
			formatter.Serialize(buffer, call);

			// Reset buffer:
			buffer.Flush();
			buffer.Position = 0;

			// Deserialize call:
			call = (MockableCall)formatter.Deserialize(buffer);

			// Verify results (expect returnValue to be non-null):
			Assert.IsNotNull(call);
			Assert.IsNotNull(call.ReturnValue, "ReturnValue is null, the old implementation issue has reoccured...");
			Assert.IsTrue(call.ReturnValue is global::System.Data.DataSet, "What the heck ? returnValue should have been a dataset !");
		}
		public void HandleCall(MockingProxy proxy, MockableCall call) {
			using (new RecorderManager.Lock()) {
				call.SetResult(InvokeOnServer(proxy, call));
				RecorderManager.RecordCall(call);
			}
		}
		/// <summary>
		/// Handles the call by playing it back.
		/// </summary>
		public void HandleCall(MockingProxy proxy, MockableCall call) {
			RecorderManager.PlayBackCall(call);
		}
		public void Serialization04Test()
		{
			MemoryStream buffer = new MemoryStream();
			Sfmt.Soap.SoapFormatter formatter = new Sfmt.Soap.SoapFormatter();
			formatter.AssemblyFormat = Sfmt.FormatterAssemblyStyle.Simple;

			// Create some call:
			MockingProxy callee = new MockingProxy(typeof(Sample.FooBar), null, "m1");
			MockableCall call = new MockableCall(callee, typeof(Sample.FooBar).GetMethod("IsItTrue"), new object[] { true });
			call.SetCallResult(true);

			// Serialize it:
			formatter.Serialize(buffer, call);
			buffer.Flush();

			// Deserialize it:
			buffer.Position = 0;
			MockableCall deserializedCall = (MockableCall)formatter.Deserialize(buffer);

			// Test result:
			Assert.IsNotNull(deserializedCall);
			Assert.IsFalse(deserializedCall.IsConstructorCall);
			Assert.IsNotNull(deserializedCall.Method);
			Assert.AreEqual("IsItTrue", deserializedCall.Method.Name);
			Assert.IsFalse(deserializedCall.ReturnValue is string, "ReturnValue of type bool was read back through soap serialization as a string.");
			Assert.IsTrue(deserializedCall.ReturnValue is bool);
			Assert.IsTrue(deserializedCall.InArgs[0] is bool);
			Assert.IsTrue((bool)deserializedCall.ReturnValue);
			Assert.IsTrue(deserializedCall.IsCompleted);
		}
		/// <summary>
		/// Process synchronous messages through the sink chain. Mocking can be applied here.
		/// </summary>
		public IMessage SyncProcessMessage(IMessage msg) {
			IMethodCallMessage mcm = (IMethodCallMessage)msg;
			IMethodReturnMessage result;
			if (RecorderManager.IsPlaying && RemotingMockService.IsUriToMock(mcm.Uri)) {
				MockingProxy proxy = new MockingProxy(Type.GetType(mcm.TypeName), new RemotingPlayBackMocker(), mcm.Uri);
				result = (IMethodReturnMessage)proxy.Invoke(msg);
			} else if (RecorderManager.IsRecording && !RecorderManager.IsInCall && RemotingMockService.IsUriToMock(mcm.Uri)) {
				MockingProxy proxy = new MockingProxy(Type.GetType(mcm.TypeName), null, mcm.Uri);
				MockableCall call = new MockableCall(proxy, mcm);
				using (new RecorderManager.Lock()) {
					result = SyncProcessMessageOnServer(mcm);
					call.SetResult(result);
					RecorderManager.RecordCall(call);
				}
			} else {
				result = (IMethodReturnMessage)nextMessageSink.SyncProcessMessage(msg);
			}
			return result;
		}
		public void ScenarioPlayTest()
		{

			using (RecorderManager.NewRecordingSession("test"))
			{

				// Make a callee, not really used but needed to record a constructor call:
				MockingProxy callee = new MockingProxy(typeof(Sample.Account), null, "m1");

				// Push some calls in the recorder:
				MockableCall lastcall;
				CurrentRecorder.RecordCall(lastcall = new MockableCall(callee, typeof(Sample.Account).GetConstructor(new Type[] { typeof(Sample.CurrencyUnit) }), null));
				lastcall.SetConstructionResult("acc");
				CurrentRecorder.RecordCall(lastcall = new MockableCall(callee, typeof(Sample.Account).GetMethod("Deposit"), null));
				lastcall.SetCallResult();
				CurrentRecorder.RecordCall(lastcall = new MockableCall(callee, typeof(Sample.Account).GetMethod("Withdraw"), null));
				lastcall.SetCallResult();
				CurrentRecorder.RecordCall(lastcall = new MockableCall(callee, typeof(Sample.Account).GetProperty("Balance").GetGetMethod(), null));
				lastcall.SetCallResult(10m);
			}

			using (RecorderManager.NewPlayBackSession("test", true))
			{
				// Register types to mock:
				MockService.AddTypeToMock(typeof(Sample.Account));

				// Play scenario:
				Sample.Account acc = new Sample.Account(Sample.CurrencyUnit.EUR);
				acc.Deposit(100m);
				acc.Withdraw(25m);
				Decimal balance = acc.Balance;

				// Checks:
				Assert.AreEqual(10m, balance); // Does not match the scenario, but the mocking result !
			}
		}
		public void IsInOutParameterTest()
		{
			// Create call:
			MockingProxy callee = new MockingProxy(typeof(Sample.FooBar), null, "m1");
			MockableCall call = new MockableCall(callee, typeof(Sample.FooBar).GetMethod("SomeMethodWithInsAndOuts"), new object[] { 1, 2, null, 3 });
			// Check in parameters:
			foreach (global::System.Reflection.ParameterInfo param in call.GetInParameters())
			{
				Assert.IsTrue(call.IsParameterIn(param.Position));
			}
			// Check out parameters:
			foreach (global::System.Reflection.ParameterInfo param in call.GetOutParameters())
			{
				Assert.IsTrue(call.IsParameterOut(param.Position));
			}
			// All params must be IN, OUT or IN/OUT:
			foreach (global::System.Reflection.ParameterInfo param in call.Method.GetParameters())
			{
				Assert.IsTrue(call.IsParameterIn(param.Position) || call.IsParameterOut(param.Position));
			}
		}
		public void GetParametersTest()
		{
			// Create call:
			MockingProxy callee = new MockingProxy(typeof(Sample.FooBar), null, "m1");
			MockableCall call = new MockableCall(callee, typeof(Sample.FooBar).GetMethod("SomeMethodWithInsAndOuts"), new object[] { 1, 2, null, 3 });
			// Check parameters:
			Assert.AreEqual(3, call.GetInParameters().Length, "Input parameters count mismatch.");
			Assert.AreEqual(2, call.GetOutParameters().Length, "Output parameters count mismatch.");
		}
Example #24
0
        private MockableCall(SerializationInfo info, StreamingContext context)
        {
            // Retrieve serialization version:
            string  assemblyVersion      = info.GetString("assemblyVersion");
            decimal serializationVersion = info.GetDecimal("serializationVersion");

            // Retrieve callee:
            this.callee = new MockingProxy(Type.GetType(info.GetString("calleeType")), new PlayBackMocker(), info.GetString("calleeInstanceName"));
            // Retrieve isConstructorCall:
            this.isConstructorCall = info.GetBoolean("isConstructorCall");
            // Retrieve method:
            Type methodType = Type.GetType(info.GetString("methodType"));

            string[] methodSignatureStr = (string[])info.GetValue("methodSignature", typeof(string[]));
            Type[]   methodSignature    = new Type[methodSignatureStr.Length];
            for (int i = 0; i < methodSignatureStr.Length; i++)
            {
                methodSignature[i] = Type.GetType(methodSignatureStr[i]);
            }
            if (this.isConstructorCall)
            {
                this.method = methodType.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, methodSignature, null);
            }
            else
            {
                this.method = methodType.GetMethod(info.GetString("methodName"), BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, methodSignature, null);
            }
            // Retrieve inArgs:
            this.inArgs = (object[])info.GetValue("inArgs", typeof(object[]));
            object[] inArgsSubstitutions = (object[])info.GetValue("inArgsMockers", typeof(object[]));
            foreach (object[] subst in inArgsSubstitutions)
            {
                MockingProxy proxy = new MockingProxy(Type.GetType((string)subst[1]), new PlayBackMocker(), (string)subst[2]);
                this.inArgs[(int)subst[0]] = proxy.GetTransparentProxy();
            }
            // Retrieve outArgs:
            this.outArgs = (object[])info.GetValue("outArgs", typeof(object[]));
            object[] outArgsSubstitutions = (object[])info.GetValue("outArgsMockers", typeof(object[]));
            if (outArgs != null)
            {
                foreach (object[] subst in outArgsSubstitutions)
                {
                    MockingProxy proxy = new MockingProxy(Type.GetType((string)subst[1]), new PlayBackMocker(), (string)subst[2]);
                    this.outArgs[(int)subst[0]] = proxy.GetTransparentProxy();
                }
            }
            // Retrieve returnValue:
            bool returnValueMocked = info.GetBoolean("returnValueMocked");
            Type returnValueType   = Type.GetType(info.GetString("returnValueType"));

            if (returnValueMocked)
            {
                MockingProxy proxy = new MockingProxy(Type.GetType(info.GetString("returnValueType")), new PlayBackMocker(), info.GetString("returnValueName"));
                this.returnValue = proxy.GetTransparentProxy();
            }
            else
            {
                this.returnValue = info.GetValue("returnValue", returnValueType);
            }
            // Retrieve exception:
            this.exception = (Exception)info.GetValue("exception", typeof(Exception));
            if (exception == null)
            {
                string exceptionType = info.GetString("exceptionType");
                if (exceptionType != null)
                {
                    this.exception = (Exception)Type.GetType(exceptionType).GetConstructor(new Type[] {}).Invoke(new object[] {});
                }
            }
            // Retrieve iscompleted & duration:
            this.isCompleted  = info.GetBoolean("isCompleted");
            this.callDuration = info.GetInt32("callDuration");
        }
		public void Serialization05Test()
		{
			MemoryStream buffer = new MemoryStream();
			Sfmt.Soap.SoapFormatter formatter = new Sfmt.Soap.SoapFormatter();
			formatter.AssemblyFormat = Sfmt.FormatterAssemblyStyle.Simple;

			// Create some call:
			MockingProxy callee = new MockingProxy(typeof(Sample.FooBar), null, "m1");
			MockableCall call = new MockableCall(callee, typeof(Sample.FooBar).GetMethod("SomeVoid"), new object[] { });
			call.SetCallResult();

			// Serialize it:
			formatter.Serialize(buffer, call);
			buffer.Flush();

			// Deserialize it:
			buffer.Position = 0;
			MockableCall deserializedCall = (MockableCall)formatter.Deserialize(buffer);

			// Test result:
			Assert.IsNotNull(deserializedCall);
			Assert.IsFalse(deserializedCall.IsConstructorCall);
			Assert.IsNotNull(deserializedCall.Method);
			Assert.AreEqual("SomeVoid", deserializedCall.Method.Name);
			Assert.IsTrue(deserializedCall.ReturnValue == null);
			Assert.IsTrue(deserializedCall.IsCompleted);
		}
		public void CreationTest()
		{
			MockingProxy callee = new MockingProxy(typeof(Sample.FooBar), null, "m1");
			MockableCall call = new MockableCall(callee, typeof(Sample.FooBar).GetMethod("SomeMethodWithInsAndOuts"), new object[] { 1, 2, null, 3 });
		}
Example #27
0
 void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
 {
     // Serialize serialization version:
     info.AddValue("assemblyVersion", System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString());
     info.AddValue("serializationVersion", 2.0m);
     // Serialize callee:
     info.AddValue("calleeType", TypeRef(callee.GetProxiedType()));
     info.AddValue("calleeInstanceName", callee.InstanceName);
     // Serialize method:
     info.AddValue("methodType", TypeRef(this.method.DeclaringType));
     info.AddValue("methodName", this.method.Name);
     ParameterInfo[] parameters         = this.method.GetParameters();
     string[]        methodSignatureStr = new string[parameters.Length];
     for (int i = 0; i < parameters.Length; i++)
     {
         methodSignatureStr[i] = TypeRef(parameters[i].ParameterType);
     }
     info.AddValue("methodSignature", methodSignatureStr);
     // Serialize isConstructorCall:
     info.AddValue("isConstructorCall", this.isConstructorCall);
     // Serialize inArgs:
     object[] inArgsSubstituted;
     object[] inArgsSubstitutions;
     SubstituteMockers(this.inArgs, out inArgsSubstituted, out inArgsSubstitutions);
     info.AddValue("inArgs", inArgsSubstituted);
     info.AddValue("inArgsMockers", inArgsSubstitutions);
     // Serialize outArgs:
     object[] outArgsSubstituted;
     object[] outArgsSubstitutions;
     if (outArgs == null)
     {
         outArgsSubstituted   = null;
         outArgsSubstitutions = null;
     }
     else
     {
         SubstituteMockers(this.outArgs, out outArgsSubstituted, out outArgsSubstitutions);
     }
     info.AddValue("outArgs", outArgsSubstituted);
     info.AddValue("outArgsMockers", outArgsSubstitutions);
     // Serialize returnValue:
     if (this.returnValue == null)
     {
         info.AddValue("returnValueMocked", false);
         info.AddValue("returnValueType", TypeRef(this.GetReturnType()));
         info.AddValue("returnValue", null);
     }
     else if (RemotingServices.IsTransparentProxy(this.returnValue))
     {
         MockingProxy rp = RemotingServices.GetRealProxy(this.returnValue) as MockingProxy;
         info.AddValue("returnValueMocked", true);
         info.AddValue("returnValueType", TypeRef(rp.ServerType));
         info.AddValue("returnValueName", rp.InstanceName);
     }
     else
     {
         info.AddValue("returnValueMocked", false);
         info.AddValue("returnValueType", TypeRef(this.GetReturnType()));
         info.AddValue("returnValue", this.returnValue);
     }
     // Serialize exception:
     if (this.exception == null)
     {
         info.AddValue("exception", null);
         info.AddValue("exceptionType", null);
     }
     else if (this.exception.GetType().IsSerializable)
     {
         info.AddValue("exception", this.exception);
         info.AddValue("exceptionType", null);
     }
     else
     {
         info.AddValue("exception", null);
         info.AddValue("exceptionType", TypeRef(this.exception.GetType()));
     }
     // Serialize icompleted & duration:
     info.AddValue("isCompleted", this.isCompleted);
     info.AddValue("callDuration", this.callDuration);
 }
Example #28
0
		/// <summary>
		/// Implements IMocker.
		/// </summary>
		public void HandleCall(MockingProxy proxy, MockableCall call) {
			try {
				IExpectedCall expectedCall = DequeueExpectedCall();
				expectedCall.Replay(call);
			} catch (ArgumentOutOfRangeException) {
				throw new ReplayMockException(call, "Call not expected.");
			}
		}
Example #29
0
		private MockableCall(SerializationInfo info, StreamingContext context) {
			// Retrieve serialization version:
			string assemblyVersion = info.GetString("assemblyVersion");
			decimal serializationVersion = info.GetDecimal("serializationVersion");
			// Retrieve callee:
			this.callee = new MockingProxy(Type.GetType(info.GetString("calleeType")), new PlayBackMocker(), info.GetString("calleeInstanceName"));
			// Retrieve isConstructorCall:
			this.isConstructorCall = info.GetBoolean("isConstructorCall");
			// Retrieve method:
			Type methodType = Type.GetType(info.GetString("methodType"));
			string[] methodSignatureStr = (string[])info.GetValue("methodSignature", typeof(string[]));
			Type[] methodSignature = new Type[methodSignatureStr.Length];
			for(int i=0; i<methodSignatureStr.Length; i++) methodSignature[i] = Type.GetType(methodSignatureStr[i]);
			if (this.isConstructorCall) {
				this.method = methodType.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, methodSignature, null);
			} else {
				this.method = methodType.GetMethod(info.GetString("methodName"), BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, methodSignature, null);
			}
			// Retrieve inArgs:
			this.inArgs = (object[])info.GetValue("inArgs", typeof(object[]));
			object[] inArgsSubstitutions = (object[])info.GetValue("inArgsMockers", typeof(object[]));
			foreach(object[] subst in inArgsSubstitutions) {
				MockingProxy proxy = new MockingProxy(Type.GetType((string)subst[1]), new PlayBackMocker(), (string)subst[2]);
				this.inArgs[(int)subst[0]] = proxy.GetTransparentProxy();
			}
			// Retrieve outArgs:
			this.outArgs = (object[])info.GetValue("outArgs", typeof(object[]));
			object[] outArgsSubstitutions = (object[])info.GetValue("outArgsMockers", typeof(object[]));
			if (outArgs != null) {
				foreach(object[] subst in outArgsSubstitutions) {
					MockingProxy proxy = new MockingProxy(Type.GetType((string)subst[1]), new PlayBackMocker(), (string)subst[2]);
					this.outArgs[(int)subst[0]] = proxy.GetTransparentProxy();
				}
			}
			// Retrieve returnValue:
			bool returnValueMocked = info.GetBoolean("returnValueMocked");
			Type returnValueType = Type.GetType(info.GetString("returnValueType"));
			if (returnValueMocked) {
				MockingProxy proxy = new MockingProxy(Type.GetType(info.GetString("returnValueType")), new PlayBackMocker(), info.GetString("returnValueName"));
				this.returnValue = proxy.GetTransparentProxy();
			} else {
				this.returnValue = info.GetValue("returnValue", returnValueType);
			}
			// Retrieve exception:
			this.exception = (Exception)info.GetValue("exception", typeof(Exception));
			if (exception == null) {
				string exceptionType = info.GetString("exceptionType");
				if (exceptionType != null) {
					this.exception = (Exception)Type.GetType(exceptionType).GetConstructor(new Type[] {}).Invoke(new object[] {});
				}
			}
			// Retrieve iscompleted & duration:
			this.isCompleted = info.GetBoolean("isCompleted");
			this.callDuration = info.GetInt32("callDuration");
		}
		/// <summary>
		/// Creates a mocked instance for the given serverType.
		/// </summary>
		/// <param name="serverType">The type for which to create an instance.
		/// Should be the type decorated by this attribute.</param>
		protected virtual MarshalByRefObject CreateMockedInstance(Type serverType) {
			IMocker customMocker;
			// Retrieve customMockerType from name:
			if (this.customMockerType == null)
				this.customMockerType = Type.GetType(customMockerTypeName);
			// Check customMockerType exists:
			if (this.customMockerType == null)
				throw new TypeLoadException(String.Format("The typename \"{0}\" configured as mocker on a CustomMockAttribute could not be resolved.", this.customMockerTypeName));
			// Create custom mocker:
			customMocker = (IMocker)customMockerType.GetConstructor(new Type[] {}).Invoke(new object[] {});
			// Create proxy, return transparent proxy:
			RealProxy rp;
			if (RecorderManager.IsRecording) {
				rp = new MockingProxy(serverType, customMocker, RecorderManager.GetNextInstanceName(serverType));
			} else {
				rp = new MockingProxy(serverType, customMocker, null);
			}
			return (MarshalByRefObject)rp.GetTransparentProxy();
		}
Example #31
0
		internal void Initialize(MockingProxy proxy) {
			this.proxy = proxy;
		}