Created
October 18, 2018 18:04
-
-
Save kzu/d301fd17d037b4bfbbcdde1b8d1267aa to your computer and use it in GitHub Desktop.
Mocking Xamarin.Forms
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public abstract class FormsTests | |
| { | |
| static FormsTests() | |
| { | |
| // Force loading of XAML assembly. | |
| Debug.WriteLine(typeof(XamlCompilationAttribute).FullName); | |
| var mock = new Mock<IPlatformServices> { DefaultValue = DefaultValue.Mock }; | |
| mock.Setup(x => x.BeginInvokeOnMainThread(It.IsAny<Action>())) | |
| .Callback<Action>(action => action()); | |
| mock.Setup(x => x.CreateTicker()).Returns(new TestTicker()); | |
| mock.Setup(x => x.GetAssemblies()).Returns(() => AppDomain.CurrentDomain.GetAssemblies()); | |
| mock.Setup(x => x.GetNamedSize(It.IsAny<NamedSize>(), It.IsAny<Type>(), It.IsAny<bool>())) | |
| .Returns((NamedSize size, Type targetElement, bool useOldSizes) => | |
| { | |
| switch (size) | |
| { | |
| case NamedSize.Default: | |
| return 10; | |
| case NamedSize.Micro: | |
| return 4; | |
| case NamedSize.Small: | |
| return 8; | |
| case NamedSize.Medium: | |
| return 12; | |
| case NamedSize.Large: | |
| return 16; | |
| default: | |
| throw new ArgumentOutOfRangeException("size"); | |
| } | |
| }); | |
| mock.Setup(x => x.StartTimer(It.IsAny<TimeSpan>(), It.IsAny<Func<bool>>())) | |
| .Callback((TimeSpan interval, Func<bool> callback) => | |
| { | |
| Timer timer = null; | |
| TimerCallback onTimeout = o => | |
| { | |
| if (callback()) | |
| return; | |
| timer.Dispose(); | |
| }; | |
| timer = new Timer(onTimeout, null, interval, interval); | |
| }); | |
| Device.PlatformServices = mock.Object; | |
| Device.SetIdiom(TargetIdiom.Desktop); | |
| Accessor.SetDesignMode(true); | |
| DependencyService.Register<SystemResourcesProvider>(); | |
| } | |
| class SystemResourcesProvider : ISystemResourcesProvider | |
| { | |
| IResourceDictionary resources = new Mock<IResourceDictionary> { DefaultValue = DefaultValue.Mock }.Object; | |
| public IResourceDictionary GetSystemResources() => resources; | |
| } | |
| class TestTicker : Ticker | |
| { | |
| bool enabled; | |
| protected override void EnableTimer() | |
| { | |
| enabled = true; | |
| while (enabled) | |
| SendSignals(16); | |
| } | |
| protected override void DisableTimer() => enabled = false; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment