PageRenderTime 83ms CodeModel.GetById 40ms app.highlight 3ms RepoModel.GetById 37ms app.codeStats 0ms

/src/UnitTests/AOP/FieldInterceptionTests.cs

http://github.com/philiplaureano/LinFu
C# | 67 lines | 53 code | 13 blank | 1 comment | 1 complexity | 805c591602a5d69f50d4deb772648128 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;
 8
 9namespace LinFu.UnitTests.AOP
10{
11    public class FieldInterceptionTests
12    {
13        public class FieldInterceptorImpl : IFieldInterceptor
14        {
15            public bool CanIntercept(IFieldInterceptionContext context)
16            {
17                return true;
18            }
19
20            public object GetValue(IFieldInterceptionContext context)
21            {
22                return "freeze!";
23            }
24
25            public object SetValue(IFieldInterceptionContext context, object value)
26            {
27                // Prevent any setter calls by replacing the setter value
28                return "freeze!";
29            }
30        }
31
32        [Fact]
33        public void ShouldSetAndGetTheSameFieldValue()
34        {
35            var myLibrary = AssemblyDefinition.ReadAssembly("SampleLibrary.dll");
36            var module = myLibrary.MainModule;
37
38            foreach (TypeDefinition type in myLibrary.MainModule.Types)
39            {
40                if (!type.FullName.Contains("SampleClassWithReadOnlyField"))
41                    continue;
42
43                type.InterceptAllFields();
44            }
45
46            var loadedAssembly = myLibrary.ToAssembly();
47            var targetType = (from t in loadedAssembly.GetTypes()
48                where t.Name.Contains("SampleClassWithReadOnlyField")
49                select t).First();
50
51            var instance = Activator.CreateInstance(targetType);
52            Assert.NotNull(instance);
53
54            var host = (IFieldInterceptionHost) instance;
55            Assert.NotNull(host);
56
57            host.FieldInterceptor = new FieldInterceptorImpl();
58
59            var targetProperty = targetType.GetProperty("Value");
60            targetProperty?.SetValue(instance, "OtherValue", null);
61
62            var actualValue = targetProperty?.GetValue(instance, null);
63
64            Assert.Equal("freeze!", actualValue);
65        }
66    }
67}