Created
April 14, 2017 13:07
-
-
Save pawelgradecki/d2e06d9f8f461ebf0c439118dd50f733 to your computer and use it in GitHub Desktop.
Plugin interface mocking
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static class Extensions | |
{ | |
public static T Mock<T>(this Entity entity) | |
{ | |
return InterfaceMocker.Mock<T>(entity); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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