/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

  1. using System;
  2. using System.Linq;
  3. using LinFu.AOP.Cecil.Extensions;
  4. using LinFu.AOP.Interfaces;
  5. using LinFu.Reflection.Emit;
  6. using Mono.Cecil;
  7. using Xunit;
  8. namespace LinFu.UnitTests.AOP
  9. {
  10. public class FieldInterceptionTests
  11. {
  12. public class FieldInterceptorImpl : IFieldInterceptor
  13. {
  14. public bool CanIntercept(IFieldInterceptionContext context)
  15. {
  16. return true;
  17. }
  18. public object GetValue(IFieldInterceptionContext context)
  19. {
  20. return "freeze!";
  21. }
  22. public object SetValue(IFieldInterceptionContext context, object value)
  23. {
  24. // Prevent any setter calls by replacing the setter value
  25. return "freeze!";
  26. }
  27. }
  28. [Fact]
  29. public void ShouldSetAndGetTheSameFieldValue()
  30. {
  31. var myLibrary = AssemblyDefinition.ReadAssembly("SampleLibrary.dll");
  32. var module = myLibrary.MainModule;
  33. foreach (TypeDefinition type in myLibrary.MainModule.Types)
  34. {
  35. if (!type.FullName.Contains("SampleClassWithReadOnlyField"))
  36. continue;
  37. type.InterceptAllFields();
  38. }
  39. var loadedAssembly = myLibrary.ToAssembly();
  40. var targetType = (from t in loadedAssembly.GetTypes()
  41. where t.Name.Contains("SampleClassWithReadOnlyField")
  42. select t).First();
  43. var instance = Activator.CreateInstance(targetType);
  44. Assert.NotNull(instance);
  45. var host = (IFieldInterceptionHost) instance;
  46. Assert.NotNull(host);
  47. host.FieldInterceptor = new FieldInterceptorImpl();
  48. var targetProperty = targetType.GetProperty("Value");
  49. targetProperty?.SetValue(instance, "OtherValue", null);
  50. var actualValue = targetProperty?.GetValue(instance, null);
  51. Assert.Equal("freeze!", actualValue);
  52. }
  53. }
  54. }