Skip to content

Instantly share code, notes, and snippets.

@pawelgradecki
Created April 14, 2017 13:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pawelgradecki/d2e06d9f8f461ebf0c439118dd50f733 to your computer and use it in GitHub Desktop.
Save pawelgradecki/d2e06d9f8f461ebf0c439118dd50f733 to your computer and use it in GitHub Desktop.
Plugin interface mocking
public static class Extensions
{
public static T Mock<T>(this Entity entity)
{
return InterfaceMocker.Mock<T>(entity);
}
}
static class InterfaceMocker
{
public static T Mock<T>(Entity entity)
{
var type = ProxyTypesCache.GetProxyType(entity.LogicalName);
var copy = Activator.CreateInstance(type);
(copy as Entity).Attributes = entity.Attributes;
(copy as Entity).Id = entity.Id;
if (typeof(T).IsAssignableFrom(type))
{
return (T)copy;
}
else
{
throw new InvalidPluginExecutionException("Cannot mock interface. Target type does not implement interface " + typeof(T).Name);
}
}
}
static class ProxyTypesCache
{
private static Dictionary<string, Type> cachedTypes = new Dictionary<string, Type>();
static ProxyTypesCache()
{
var assembly = System.Reflection.Assembly.GetExecutingAssembly();
var allTypes = assembly.GetExportedTypes();
foreach (var type in allTypes)
{
if (typeof(Entity).IsAssignableFrom(type))
{
cachedTypes.Add(type.GetCustomAttribute<EntityLogicalNameAttribute>().LogicalName, type);
}
}
}
public static Type GetProxyType(string logicalName)
{
return cachedTypes[logicalName];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment