using System; using UnitTestSharp; namespace Vellum.UnitTests { public class RuntimeEmitTests : TestFixture { public static RuntimeEmit.Method NewMethod() { return new RuntimeEmit.Method("Nothing", typeof(void), new Type[0], typeof(RuntimeEmitTests).Module); } public class IsAvailableTests : TestFixture { public void WhereTheTestsRun_IsTrue() { CheckTrue(RuntimeEmit.IsAvailable); } } public class MethodTests : TestFixture { public void MethodThatReturns_BecomesADelegateOfTheTypeAsked() { Delegate made = NewMethod().Emit("Ret").CreateDelegate(typeof(System.Action)); CheckEqual(typeof(System.Action), made.GetType()); ((System.Action)made)(); } public void OpCodeThatDoesntExist_Throws() { CheckThrow(typeof(ArgumentException)); NewMethod().Emit("NoSuchOpCode"); } public void EmitReturnsTheMethodSoCallsChain() { RuntimeEmit.Method method = NewMethod(); CheckTrue(ReferenceEquals(method, method.Emit("Nop"))); } public void MethodThatTakesAnArgument_CanStoreIntoAField() { var method = new RuntimeEmit.Method("Store", typeof(void), new[] { typeof(Bucket), typeof(string) }, typeof(Bucket).Module); method.Emit("Ldarg_0").Emit("Ldarg_1").Emit("Stfld", typeof(Bucket).GetField(nameof(Bucket.Plain))) .Emit("Ret"); var store = (System.Action)method.CreateDelegate(typeof(System.Action)); var bucket = new Bucket("s", 1); store(bucket, "stored"); CheckEqual("stored", bucket.Plain); } public void MethodThatCastsAndCallsAConstructor_RunsItOnAnObject() { var method = new RuntimeEmit.Method("Construct", typeof(void), new[] { typeof(object), typeof(int) }, typeof(Counted).Module); method.Emit("Ldarg_0").Emit("Castclass", typeof(Counted)).Emit("Ldarg_1") .Emit("Call", typeof(Counted).GetConstructor(new[] { typeof(int) })).Emit("Ret"); var construct = (System.Action)method.CreateDelegate(typeof(System.Action)); var counted = FieldWriterTests.Blank(); construct(counted, 7); CheckEqual(7, counted.Number); } } } }