【问题标题】:How can I setup Property Injection for MvvmCross tests?如何为 MvvmCross 测试设置属性注入?
【发布时间】:2015-01-29 20:51:09
【问题描述】:

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

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

在我的视图模型中,我有几个公共接口属性,如下所示:

public void IDataService DataService { get; set; }

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

使用MvxIoCSupportingTest时如何正确设置属性注入?

【问题讨论】:

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


    【解决方案1】:

    根据 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

    【讨论】:

      【解决方案2】:

      要覆盖 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() 虚拟方法,那肯定会更好。

      【讨论】:

        【解决方案3】:

        一定是报错:

        未能为 Viewmodel 类型构造和初始化 ViewModel。你可能错过了:

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

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

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

        希望对你有所帮助。

        【讨论】:

          猜你喜欢
          • 2019-09-26
          • 2011-09-26
          • 1970-01-01
          • 1970-01-01
          • 2022-01-23
          • 1970-01-01
          • 1970-01-01
          • 2020-02-07
          • 1970-01-01
          相关资源
          最近更新 更多