【问题标题】:How can I test methods containing Application.Current.Properties.ContainsKey("token")如何测试包含 Application.Current.Properties.ContainsKey("token") 的方法
【发布时间】:2018-03-04 20:20:54
【问题描述】:

我正在尝试测试我的 Xamarin 应用程序的登录,但为了使该应用程序正常工作,我必须创建一个令牌。其方法如下所示:

public string RetrieveToken()
{
    if (Application.Current.Properties.ContainsKey("token"))
    {
         return Application.Current.Properties["token"] as string;
    }
    return null;
}

但是当测试运行时,我收到 NullReferenceError,因为 Application.Current.Properties.ContainsKey("token") 不能在测试中使用。 所以我的问题是是否有办法避免这种情况。

【问题讨论】:

  • 将实现问题封装在抽象背后。然后可以在单独对代码进行单元测试时模拟抽象。
  • 尝试将链接器行为设置为无
  • 由于Application 是实例化/初始化的Xamarin.Forms 应用程序的成员,因此是基于平台的,因此直接测试此类代码将属于“UI 测试”stackoverflow.com/a/42939217/4984832(我在我的回答中描述三个级别的“单元测试”)否则你需要抽象/模拟它以便对其进行经典的单元测试。

标签: c# unit-testing xamarin login xamarin.forms


【解决方案1】:

您是否在此项目中使用任何依赖注入?在为 ViewModel 编写单元测试时,我使用 Application.Current.Resources 做了类似的事情。

您可以将Application.Current.Properties 注册为服务的属性。然后为您的项目使用该服务并在您的测试中模拟该属性。

例如,如果您使用的是 Microsoft Unity DI,您可以执行以下操作:

public interface IAppPropertyService
{
    IDictionary<string, object> Properties { get; set; }
}

public class AppPropertyService : IAppPropertyService
{
    public const string AppPropertiesName = "AppProperties";

    public IDictionary<string, object> Properties { get; set; }

    public AppPropertyService([IocDepndancy(AppPropertiesName)] IDictionary<string, object> appProperties)
    {
        Properties = appProperties;
    }
}

然后在您的应用中注册这样的服务:

Container.RegisterInstance<IDictionary<string, object>>(AppPropertyService.AppPropertiesName, Application.Current.Properties);
Container.RegisterType<IAppPropertyService, AppPropertyService>();

在您的测试中使用 Application.Current.Properties 的模拟版本,例如只是一个字典:

Container.RegisterInstance<IDictionary<string, object>>(AppPropertyService.AppPropertiesName, new Dictionary<string, object>());
Container.RegisterType<IAppPropertyService, AppPropertyService>();

请务必在您的项目中使用 PropertyService 而不是 Application.Current.Properties,如下所示:

public string RetrieveToken()
{
    var propertyService = Container.Resolve<IAppPropertyService>();

    if (propertyService.Properties.ContainsKey("token"))
    {
         return propertyService.Properties["token"] as string;
    }
    return null;
}

【讨论】:

    猜你喜欢
    • 2019-11-12
    • 1970-01-01
    • 2011-10-29
    • 2020-09-25
    • 2023-03-19
    • 1970-01-01
    • 2022-06-23
    • 1970-01-01
    • 2021-12-23
    相关资源
    最近更新 更多