MVVM在单元测试MxvAsyncCommand

时间:2018-12-03 16:29:43

标签: mvvmcross

我们最近已升级到MvvMCross 6.2.2,并注意到我们必须更改为使用Mvx.IoCProvider。

我们发现,如果我们在ViewModel中构造MvxAsyncCommand,则会在所有调用此构造函数的单元测试中导致空引用异常

*

Result StackTrace:  
at MvvmCross.Commands.MvxCommandBase..ctor()
   at MvvmCross.Commands.MvxAsyncCommand..ctor(Func`1 execute, Func`1 canExecute, Boolean allowConcurrentExecutions)
   at App.Mobile.Core.ViewModels.TestViewModel..ctor(IMvxNavigationService navigation, ITestService encService, ILogger logger)
   at App.Mobile.Core.UnitTests.TestViewModelTests.<TestViewModel_Prepare>d__1.MoveNext()

*

在github中查看源代码,原因是Mvx.IocProvider为空。

public MvxCommandBase()
    {
        if (!Mvx.IoCProvider.TryResolve<IMvxCommandHelper>(out _commandHelper))
            _commandHelper = new MvxWeakCommandHelper();

        var alwaysOnUIThread = MvxSingletonCache.Instance == null || MvxSingletonCache.Instance.Settings.AlwaysRaiseInpcOnUserInterfaceThread;
        ShouldAlwaysRaiseCECOnUserInterfaceThread = alwaysOnUIThread;
    }

已在“开发”分支中实现了修复程序,但是nuget上不提供此修复程序。

public MvxCommandBase()
    {
        // fallback on MvxWeakCommandHelper if no IoC has been set up
        if (!Mvx.IoCProvider?.TryResolve(out _commandHelper) ?? true)
            _commandHelper = new MvxWeakCommandHelper();

        // default to true if no Singleton Cache has been set up
        var alwaysOnUIThread = MvxSingletonCache.Instance?.Settings.AlwaysRaiseInpcOnUserInterfaceThread ?? true;
        ShouldAlwaysRaiseCECOnUserInterfaceThread = alwaysOnUIThread;
    }

是否有人知道在我们的单元测试项目中初始化此IoCProvider的解决方法。

1 个答案:

答案 0 :(得分:1)

您可以看到here,通过获取IoCProvider的单例来解决IMvxIoCProvider

public static IMvxIoCProvider IoCProvider => MvxSingleton<IMvxIoCProvider>.Instance;

因此,您要做的就是初始化IMvxIoCProvider。 例如,您可以使用this test,因此,要对其进行初始化,您必须执行以下操作:

MvxSingleton.ClearAllSingletons(); // This should be done in the test to clear all references of previous tests if necessary.
var instance = MvxIoCProvider.Initialize();

HIH