using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics; using System.Reflection; namespace RMock { /// /// Facilitates the creation of mock classes for FCL objects. /// internal static class MockServices { /// /// Instantiates T without calling a constructor. /// Works well with otherwise uninstantiable objects. /// /// Anything that does NOT derive /// from ContextBoundObject. /// A dictionary of values to initialize /// the object in place of a constructor. /// The newly created and instantiated object. public static T Create(Dictionary Values) { if (Values == null) throw new ArgumentNullException("Values", "Values is null."); return Fill( CreateBlank(), Values); } private static T CreateBlank() { if (typeof(ContextBoundObject).IsAssignableFrom(typeof(T)) == true) { throw new ApplicationException( "You can't use types that derive from ContextBoundObject."); } return (T)System.Runtime.Serialization.FormatterServices .GetUninitializedObject(typeof(T)); } private static T Fill(T Source, Dictionary Values) { if (Source == null) throw new ArgumentNullException("Source", "Source is null."); if (Values == null) throw new ArgumentNullException("Values", "Values is null"); if (Values.Count == 0) return Source; FieldInfo[] EventFields = typeof(T) .GetFields( BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly); if (EventFields != null && EventFields.Count() > 0) { foreach (FieldInfo Field in EventFields) { if (Values.ContainsKey(Field.Name) == true && Field.FieldType .IsAssignableFrom(Values[Field.Name] .GetType()) == true) { Field.SetValue(Source, Values[Field.Name]); } } } return Source; } } }