单元测试-棱镜-Xamarin.Forms-INavigationService问题

时间:2019-01-28 03:59:41

标签: unit-testing xamarin.forms prism

我最近开始研究适用于iOS和Android的Xamarin.Forms应用。我添加了带有xUnit软件包的单元测试项目。

截至目前,该应用程序具有一个视图和一个视图模型。我想把一切都整理好。因此,视图模型只有一个属性。该属性被初始化为string.empty。所以我只是检查以确保它不为空。视图模型依赖于NagivationService。

在我的App.xaml.cs中-视图和视图模型已注册用于导航。

protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
    containerRegistry.RegisterForNavigation<NavigationPage>();
    containerRegistry.RegisterForNavigation<ViewAPage, ViewAPageViewModel>();
}

我创建了该应用的模拟

public class AppMock : App
{
    public AppMock(IPlatformInitializer initializer)
        : base(initializer) {}

    // Added as a work around
    public new INavigationService NavigationService => base.NavigationService;

    protected override void RegisterTypes(IContainerRegistry containerRegistry)
    {
        base.RegisterTypes(containerRegistry);
        containerRegistry.Register<ILoggerFacade, XunitTestOutputLogger>();
    }
}

测试治具

public class ViewAViewModelFixture : FixtureBase, IDisposable
{
    public ViewAViewModelFixture(ITestOutputHelper testOutputHelper)
        : base(testOutputHelper) {
    }

    private AppMock CreateApp()
    {
        var initializer = new XunitPlatformInitializer(_testOutputHelper);
        return new AppMock(initializer);
    }

    protected AppMock App
    {
        get
        {
            if ( app == null )
            {
                this.App = CreateApp();
            }
            return this.app;
        }
        set
        {
            this.app = value;
        }
    }
    private AppMock app;

    [Fact]
    public void Email_IsEmpty()
    {            
        ViewAViewModel vm = (ViewAViewModel)this.App.Container.Resolve(typeof(ViewAViewModel));

        string email = vm.Email;

        Assert.Equal(expected: string.Empty, actual: email);
    }

    public void Dispose()
    {
        PageNavigationRegistry.ClearRegistrationCache();
    }
}

当我尝试运行上述测试时,出现以下错误:

Message: Unity.Exceptions.ResolutionFailedException : Resolution of the dependency failed, type = 'App.ViewModels.ViewAViewModel', name = '(none)'.
Exception occurred while: while resolving.
Exception is: InvalidOperationException - The current type, Prism.Navigation.INavigationService, is an interface and cannot be constructed. Are you missing a type mapping?

我不确定我缺少什么。当我在Android模拟器或iOS模拟器中本地运行该应用程序时,它可以正常运行。所以我尝试了以下方法:

[Fact]
public void Email_IsEmpty()
{
    var app = this.App;
    var NavService = app.NavigationService;

    NavService.NavigateAsync("/ViewA");

    ViewA view = (ViewA)this.App.MainPage;

    Assert.IsType<ViewAViewModel>(view.BindingContext);
    ViewAViewModel vm = view.BindingContext as ViewAViewModel;

    string email = vm.Email;

    Assert.Equal(expected: string.Empty, actual: email);
}

此测试通过,而另一测试显然失败。

有人看到我想念的东西吗?

0 个答案:

没有答案