/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

  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. using SampleLibrary;
  9. using SampleLibrary.AOP;
  10. namespace LinFu.UnitTests.AOP
  11. {
  12. public class NewOperatorInterceptionTests : BaseTestFixture
  13. {
  14. private class OtherSampleService : ISampleService
  15. {
  16. public void DoSomething()
  17. {
  18. }
  19. }
  20. [Fact]
  21. public void ShouldInterceptObjectInstantiation()
  22. {
  23. var assembly = AssemblyDefinition.ReadAssembly("SampleLibrary.dll");
  24. var module = assembly.MainModule;
  25. var typeName = "SampleClassWithNewInstanceCall";
  26. var targetType = (from TypeDefinition t in module.Types
  27. where t.Name == typeName
  28. select t).First();
  29. targetType.InterceptNewInstances(declaringType => declaringType.Name == "SampleServiceImplementation");
  30. var modifiedAssembly = assembly.ToAssembly();
  31. var modifiedTargetType = modifiedAssembly.GetTypes().First(t => t.Name == typeName);
  32. var instance = Activator.CreateInstance(modifiedTargetType);
  33. Assert.NotNull(instance);
  34. // The activator will return a new OtherSampleService() instance instead
  35. // of a SampleServiceImplementation instance if the interception works
  36. var activator = new SampleTypeActivator(context => new OtherSampleService());
  37. var host = (IActivatorHost) instance;
  38. host.Activator = activator;
  39. var targetMethod = modifiedTargetType.GetMethod("DoSomething");
  40. Assert.NotNull(targetMethod);
  41. var result = targetMethod.Invoke(instance, null);
  42. Assert.NotNull(result);
  43. Assert.True(result is OtherSampleService);
  44. }
  45. }
  46. }