UnitTestApplication.cs 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. // Copyright (c) The Avalonia Project. All rights reserved.
  2. // Licensed under the MIT license. See licence.md file in the project root for full license information.
  3. using System;
  4. using Avalonia.Input;
  5. using Avalonia.Layout;
  6. using Avalonia.Platform;
  7. using Avalonia.Styling;
  8. using Avalonia.Controls;
  9. using Avalonia.Rendering;
  10. namespace Avalonia.UnitTests
  11. {
  12. public class UnitTestApplication : Application
  13. {
  14. private readonly TestServices _services;
  15. public UnitTestApplication(TestServices services)
  16. {
  17. _services = services ?? new TestServices();
  18. RegisterServices();
  19. }
  20. public static new UnitTestApplication Current => (UnitTestApplication)Application.Current;
  21. public TestServices Services => _services;
  22. public static IDisposable Start(TestServices services = null)
  23. {
  24. var scope = AvaloniaLocator.EnterScope();
  25. var app = new UnitTestApplication(services);
  26. AvaloniaLocator.CurrentMutable.BindToSelf<Application>(app);
  27. return scope;
  28. }
  29. public override void RegisterServices()
  30. {
  31. AvaloniaLocator.CurrentMutable
  32. .Bind<IAssetLoader>().ToConstant(Services.AssetLoader)
  33. .Bind<IFocusManager>().ToConstant(Services.FocusManager)
  34. .BindToSelf<IGlobalStyles>(this)
  35. .Bind<IInputManager>().ToConstant(Services.InputManager)
  36. .Bind<IKeyboardDevice>().ToConstant(Services.KeyboardDevice?.Invoke())
  37. .Bind<ILayoutManager>().ToConstant(Services.LayoutManager)
  38. .Bind<IRuntimePlatform>().ToConstant(Services.Platform)
  39. .Bind<IRendererFactory>().ToConstant(new RendererFactory(Services.Renderer))
  40. .Bind<IPlatformRenderInterface>().ToConstant(Services.RenderInterface)
  41. .Bind<IRenderLoop>().ToConstant(Services.RenderLoop)
  42. .Bind<IPlatformThreadingInterface>().ToConstant(Services.ThreadingInterface)
  43. .Bind<IStandardCursorFactory>().ToConstant(Services.StandardCursorFactory)
  44. .Bind<IStyler>().ToConstant(Services.Styler)
  45. .Bind<IWindowingPlatform>().ToConstant(Services.WindowingPlatform)
  46. .Bind<IApplicationLifecycle>().ToConstant(this);
  47. var styles = Services.Theme?.Invoke();
  48. if (styles != null)
  49. {
  50. Styles.AddRange(styles);
  51. }
  52. }
  53. private class RendererFactory : IRendererFactory
  54. {
  55. Func<IRenderRoot, IRenderLoop, IRenderer> _func;
  56. public RendererFactory(Func<IRenderRoot, IRenderLoop, IRenderer> func)
  57. {
  58. _func = func;
  59. }
  60. public IRenderer CreateRenderer(IRenderRoot root, IRenderLoop renderLoop)
  61. {
  62. return _func?.Invoke(root, renderLoop);
  63. }
  64. }
  65. }
  66. }