public void BuildRuntimeType_MethodInterceptors_Function_InterceptClassMethod_ReturnParentValue() { // Arrange Mock <IMockableRuntimeTypePropertyManager> managerMock = new Mock <IMockableRuntimeTypePropertyManager>(MockBehavior.Strict); var manager = managerMock.Object; MethodInfo getMethod = manager.GetType().GetMethod("GetValue"); MethodInfo setMethod = manager.GetType().GetMethod("SetValue"); string expectedValue = "base"; Func <Func <string>, string> interceptor = baseMethod => baseMethod(); MethodInterceptions interceptions = new MethodInterceptions { Interceptions = new MethodInterception[] { new DelegateMethodInterception { InterceptedMethod = typeof(ClassWithVirtualMethod).GetMethod(nameof(ClassWithVirtualMethod.FunctionToIntercept)), Delegate = interceptor } } }; // Act Stopwatch sw = Stopwatch.StartNew(); Type runtimeType = RuntimeProxyBuilder.BuildRuntimeType(typeof(ClassWithVirtualMethod), getMethod, setMethod, interceptions); ClassWithVirtualMethod impl = (ClassWithVirtualMethod)Activator.CreateInstance(runtimeType, new object[] { manager, interceptions }); string returnedValue = impl.FunctionToIntercept(); sw.Stop(); Trace.WriteLine(sw.ElapsedMilliseconds); // Assert Assert.AreEqual(expectedValue, returnedValue); }
public void BuildRuntimeType_MethodInterceptors_InterceptClassMethod() { // Arrange Mock <IMockableRuntimeTypePropertyManager> managerMock = new Mock <IMockableRuntimeTypePropertyManager>(MockBehavior.Strict); var manager = managerMock.Object; MethodInfo getMethod = manager.GetType().GetMethod("GetValue"); MethodInfo setMethod = manager.GetType().GetMethod("SetValue"); bool interceptorCalled = false; Action <Action> interceptor = (Action baseAction) => interceptorCalled = true; MethodInterceptions interceptions = new MethodInterceptions { Interceptions = new MethodInterception[] { new DelegateMethodInterception { InterceptedMethod = typeof(ClassWithVirtualMethod).GetMethod(nameof(ClassWithVirtualMethod.ActionToIntercept)), Delegate = interceptor } } }; // Act Stopwatch sw = Stopwatch.StartNew(); Type runtimeType = RuntimeProxyBuilder.BuildRuntimeType(typeof(ClassWithVirtualMethod), getMethod, setMethod, interceptions); ClassWithVirtualMethod impl = (ClassWithVirtualMethod)Activator.CreateInstance(runtimeType, new object[] { manager, interceptions }); impl.ActionToIntercept(); sw.Stop(); Trace.WriteLine(sw.ElapsedMilliseconds); // Assert Assert.IsTrue(interceptorCalled); }