如何为MvvmCross测试设置Property Injection?

时间:2015-01-29 12:13:26

标签: c# xamarin inversion-of-control mvvmcross

我正在使用MvvmCross的IoC属性注入,在我各自的Setup.cs类中初始化:

    protected override IMvxIocOptions CreateIocOptions()
    {
        return new MvxIocOptions {
            PropertyInjectorOptions = MvxPropertyInjectorOptions.All
        };
    }

在我的视图模型中,我有几个这样的公共接口属性:

public void IDataService DataService { get; set; }

运行应用时,一切正常,但单元测试失败,因为DataServicenull

使用MvxIoCSupportingTest

时,如何正确设置属性注入?

3 个答案:

答案 0 :(得分:2)

根据Stuart的回答让它工作,我必须修改它以避免私有字段和方法:

    protected new IMvxIoCProvider Ioc { get; private set; }

    protected override void ClearAll()
    {
        // fake set up of the IoC
        MvxSingleton.ClearAllSingletons();
        var iocOptions = new MvxIocOptions {
            PropertyInjectorOptions = MvxPropertyInjectorOptions.All
        };
        Ioc = MvxSimpleIoCContainer.Initialize(iocOptions);
        Ioc.RegisterSingleton(Ioc);
        Ioc.RegisterSingleton<IMvxTrace>(new TestTrace());
        MvxSingletonCache.Initialize();
        Ioc.RegisterSingleton<IMvxSettings>(new MvxSettings());
        MvxTrace.Initialize();
        AdditionalSetup();
    }

我还提交了直接覆盖CreateIocOptions的拉取请求,这样可以更轻松:https://github.com/MvvmCross/MvvmCross/pull/897/files

答案 1 :(得分:1)

要覆盖MvxIoCSupportingTest中使用的Ioc选项,您需要覆盖ClearAll()

    protected override void ClearAll()
    {
        // fake set up of the IoC
        MvxSingleton.ClearAllSingletons();
        _ioc = MvxSimpleIoCContainer.Initialize(/* YOUR OPTIONS HERE */);
        _ioc.RegisterSingleton(_ioc);
        _ioc.RegisterSingleton<IMvxTrace>(new TestTrace());
        InitializeSingletonCache();
        InitializeMvxSettings();
        MvxTrace.Initialize();
        AdditionalSetup();
    }

来自https://github.com/MvvmCross/MvvmCross/blob/3.5/Cirrious/Test/Cirrious.MvvmCross.Test.Core/MvxIoCSupportingTest.cs#L33

如果Test类改为使用CreateIoCOptions()虚拟方法,那肯定会更好。

答案 2 :(得分:0)

必须显示错误:

无法为Viewmodel类型构造和初始化ViewModel。你可能会失踪:

public override void Initialize() {
   CreatableTypes()
        .EndingWith("Service")
        .AsTypes()
        .RegisterAsSingleton();
}

有关详细参考,请查看以下链接。

https://stackoverflow.com/a/18946672/4373895

希望这会对你有所帮助。