我正在尝试测试 Xamarin 应用程序的登录,但为了使该应用程序正常工作,我必须创建一个 token 。其方法如下所示:
public string RetrieveToken()
{
if (Application.Current.Properties.ContainsKey("token"))
{
return Application.Current.Properties["token"] as string;
}
return null;
}
但是当测试运行时,我收到一个 NullReferenceError,因为 Application.Current.Properties.ContainsKey("token")
无法在测试中使用。
所以我的问题是是否有办法避免这种情况。
最佳答案
您在此项目中使用任何依赖注入(inject)吗?当我们为 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;
}
关于c# - 如何测试包含 Application.Current.Properties.ContainsKey ("token"的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49100005/