Skip to content

Instantly share code, notes, and snippets.

@kzu

kzu/FormsTests.cs

Created Oct 18, 2018
Embed
What would you like to do?
Mocking Xamarin.Forms
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