private string GetMethods() { var methods = new StringBuilder(); var callbackMethods = this.CallbackType.GetMethods( BindingFlags.Public | BindingFlags.Instance); foreach (var interfaceMethod in this.InterfaceType.GetMethods()) { methods.Append("public " + MockCodeGenerator.GetMethod(interfaceMethod) + "{"); var callbackMethod = this.FindMethod(callbackMethods, interfaceMethod); if (callbackMethod != null) { if (callbackMethod.ReturnType != typeof(void)) { methods.Append("return "); } methods.Append("this.callback." + MockCodeGenerator.GetMethod(callbackMethod, false) + ";"); } else { if (interfaceMethod.ReturnType != typeof(void)) { methods.Append("return " + ( interfaceMethod.ReturnType.IsClass ? "null;" : string.Format("default({0});", interfaceMethod.ReturnType.FullName))); } } methods.Append("}"); } return(methods.ToString()); }
public static T Create <T>(object callback) where T : class { var interfaceType = typeof(T); if (!interfaceType.IsInterface) { throw new NotSupportedException(); } var callbackType = callback.GetType(); var mockName = callbackType.Name + Guid.NewGuid().ToString("N"); var template = new MockCodeGenerator(mockName, interfaceType, callbackType).Code; var compilation = Compilation.Create("Mock", options: new CompilationOptions(OutputKind.DynamicallyLinkedLibrary), syntaxTrees: new[] { SyntaxTree.ParseCompilationUnit(template) }, references: new MetadataReference[] { new AssemblyFileReference(typeof(Guid).Assembly.Location), new AssemblyFileReference(interfaceType.Assembly.Location), new AssemblyFileReference(callbackType.Assembly.Location) }); var result = compilation.Emit(Mock.builder.Value); if (!result.Success) { throw new NotSupportedException(string.Join(Environment.NewLine, from diagnostic in result.Diagnostics select diagnostic.Info.GetMessage())); } return(Activator.CreateInstance(Mock.builder.Value.GetType(mockName), callback) as T); }