PageRenderTime 49ms CodeModel.GetById 44ms app.highlight 3ms RepoModel.GetById 1ms app.codeStats 0ms

/src/UnitTests/AOP/NewOperatorInterceptionTests.cs

http://github.com/philiplaureano/LinFu
C# | 57 lines | 44 code | 11 blank | 2 comment | 3 complexity | 65969e8f402409d948cc2055252064ad MD5 | raw file
 1using System;
 2using System.Linq;
 3using LinFu.AOP.Cecil.Extensions;
 4using LinFu.AOP.Interfaces;
 5using LinFu.Reflection.Emit;
 6using Mono.Cecil;
 7using Xunit;
 8using SampleLibrary;
 9using SampleLibrary.AOP;
10
11namespace LinFu.UnitTests.AOP
12{
13    public class NewOperatorInterceptionTests : BaseTestFixture
14    {
15        private class OtherSampleService : ISampleService
16        {
17            public void DoSomething()
18            {
19            }
20        }
21
22        [Fact]
23        public void ShouldInterceptObjectInstantiation()
24        {
25            var assembly = AssemblyDefinition.ReadAssembly("SampleLibrary.dll");
26
27            var module = assembly.MainModule;
28            var typeName = "SampleClassWithNewInstanceCall";
29            var targetType = (from TypeDefinition t in module.Types
30                where t.Name == typeName
31                select t).First();
32
33            targetType.InterceptNewInstances(declaringType => declaringType.Name == "SampleServiceImplementation");
34
35            var modifiedAssembly = assembly.ToAssembly();
36
37            var modifiedTargetType = modifiedAssembly.GetTypes().First(t => t.Name == typeName);
38            var instance = Activator.CreateInstance(modifiedTargetType);
39            Assert.NotNull(instance);
40
41            // The activator will return a new OtherSampleService() instance instead
42            // of a SampleServiceImplementation instance if the interception works
43            var activator = new SampleTypeActivator(context => new OtherSampleService());
44            var host = (IActivatorHost) instance;
45            host.Activator = activator;
46
47            var targetMethod = modifiedTargetType.GetMethod("DoSomething");
48            
49            Assert.NotNull(targetMethod);
50            
51            var result = targetMethod.Invoke(instance, null);
52
53            Assert.NotNull(result);
54            Assert.True(result is OtherSampleService);
55        }
56    }
57}