Created
October 31, 2009 00:21
-
-
Save jcbozonier/222852 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| using System; | |
| using System.Linq; | |
| using System.Reflection; | |
| using System.Reflection.Emit; | |
| using System.Threading; | |
| namespace MiniMock | |
| { | |
| public class Mockery | |
| { | |
| public void BooYah() | |
| { | |
| } | |
| public static T Mock<T>() | |
| { | |
| var assemblyName = new AssemblyName(); | |
| assemblyName.Name = "mockedAssembly"; | |
| var assemblyBuilder = Thread.GetDomain().DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run); | |
| var moduleBuilder = assemblyBuilder.DefineDynamicModule("tmpModule"); | |
| var typeBuilder = moduleBuilder.DefineType("MockedFoo", | |
| TypeAttributes.Public | TypeAttributes.Class, | |
| null, | |
| new[] { typeof(T) }); | |
| var mockType = typeof (T); | |
| var methods = mockType.GetMethods(); | |
| if (methods.Count() > 0) | |
| { | |
| foreach (var methodInfo in methods) | |
| { | |
| var firstMethodName = methodInfo.Name; | |
| if (_MethodReturnsValue(methodInfo)) | |
| { | |
| var returnType = methodInfo.ReturnType; | |
| var methodBuilder = typeBuilder.DefineMethod( | |
| firstMethodName, | |
| MethodAttributes.Public | MethodAttributes.Virtual, | |
| returnType, | |
| null); | |
| methodBuilder.InitLocals = true; | |
| var methodIL = methodBuilder.GetILGenerator(); | |
| methodIL.DeclareLocal(returnType); | |
| methodIL.Emit(OpCodes.Nop); | |
| methodIL.Emit(OpCodes.Ldloc_0); | |
| methodIL.Emit(OpCodes.Ret); | |
| } | |
| else | |
| { | |
| var methodBuilder = typeBuilder.DefineMethod( | |
| firstMethodName, | |
| MethodAttributes.Public | MethodAttributes.Virtual, | |
| typeof (void), | |
| null); | |
| var methodIL = methodBuilder.GetILGenerator(); | |
| methodIL.Emit(OpCodes.Nop); | |
| methodIL.Emit(OpCodes.Ret); | |
| } | |
| } | |
| } | |
| var mockedType = typeBuilder.CreateType(); | |
| var mockedObject = Activator.CreateInstance(mockedType); | |
| return (T) mockedObject; | |
| } | |
| private static bool _MethodReturnsValue(MethodInfo methodInfo) | |
| { | |
| return methodInfo.ReturnType != typeof(void); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment