For some time I am trying to make a mocking library for C# that mocks objects with just 1 line of code. I am using abstract factory pattern to know what is the object's type so that I can work with concrete factories.
I have the following Abstract factory class which I am not very happy with.
public class MockContext<T>
{
public T CreateMockObject()
{
IFactory<T> factory = null;
if (typeof(T).IsPrimitive || typeof(T) == typeof(string) || typeof(T) == typeof(decimal))
{
factory = new PrimitiveFactory<T>();
}
else if (typeof(T).IsArray)
{
factory = new ArrayFactory<T>();
}
else if (typeof(IEnumerable).IsAssignableFrom(typeof(T)))
{
factory = new CollectionFactory<T>();
}
else if (typeof(T).IsClass && typeof(T) != typeof(string))
{
factory = new ClassFactory<T>();
}
return factory.Create();
}
}
}
Which gets called by the following class
public class Mocker
{
public T MockObject<T>()
{
MockContext<T> context = new MockContext<T>();
T mockObject = context.CreateMockObject();
return mockObject;
}
}
This abstract factory instantiates other factories depending on of the object.
Here is my class factory:
public class ClassFactory<T> : IFactory<T>
{
public T Create()
{
T mockObject = (T)Activator.CreateInstance(typeof(T));
IEnumerable<PropertyInfo> properties = typeof(T).GetProperties().Where(p => p.CanWrite);
GenericMethodInvokerUtil method = new GenericMethodInvokerUtil();
foreach (PropertyInfo property in properties)
{
if (property.PropertyType == typeof(T))
throw new Exception("Circular properties are not supported!");
method.InvokeMockObject<T>(property.PropertyType, property, mockObject);
}
return mockObject;
}
}
I am using the above code as follows:
static void Main(string[] args)
{
Mocker mocker = new Mocker();
var mock = mocker.MockObject<Test>();
}
With Test being some class with properties.
Can anyone suggest how to write this better?
Maybe there is a pattern that I am not familiar with. Any help would be appreciated.
Thanks in advance.