如何解决Xamarin应用登录测试中Application.Current.Properties空引用错误?
嘿,这个问题我之前帮不少开发者踩过坑——测试环境下Application.Current确实经常掉链子,尤其是直接碰Properties的时候。给你几个实用的规避方案,按需选就行:
方案1:用依赖注入封装存储逻辑(最推荐)
别在业务代码里硬写Application.Current.Properties,把存储逻辑抽象成接口,实际环境用Application.Properties实现,测试时用内存字典模拟,彻底解耦依赖。
先定义一个通用的偏好存储接口:
public interface IAppStorage { bool ContainsKey(string key); string GetValue(string key); void SetValue(string key, string value); }
实际应用中的实现:
public class AppStorage : IAppStorage { public bool ContainsKey(string key) => Application.Current?.Properties?.ContainsKey(key) ?? false; public string GetValue(string key) { if (Application.Current?.Properties != null && Application.Current.Properties.TryGetValue(key, out var value)) return value as string; return null; } public void SetValue(string key, string value) { if (Application.Current?.Properties != null) Application.Current.Properties[key] = value; } }
测试时的模拟实现:
public class MockAppStorage : IAppStorage { private readonly Dictionary<string, string> _mockData = new Dictionary<string, string>(); public bool ContainsKey(string key) => _mockData.ContainsKey(key); public string GetValue(string key) => _mockData.TryGetValue(key, out var val) ? val : null; public void SetValue(string key, string value) => _mockData[key] = value; }
之后业务代码里通过注入IAppStorage来操作token,测试时替换成MockAppStorage,完全不用碰Application.Current。
方案2:测试初始化时手动模拟Application.Current
如果不想大改现有代码,可以在测试的初始化方法里手动创建Application实例并赋值,同时初始化Properties字典:
[TestInitialize] public void TestSetup() { // 给Application.Current赋值一个空实例 Application.Current = new Application(); // 初始化Properties避免null引用 Application.Current.Properties = new Dictionary<string, object>(); }
这样测试时Application.Current.Properties.ContainsKey("token")就不会报空错了,简单直接。
方案3:给现有代码加空值检查包装
如果只是临时救急,给token相关操作加一层空值判断的包装方法:
private bool TokenExists() { // 先检查Application.Current和Properties是否为null if (Application.Current == null || Application.Current.Properties == null) { // 测试环境下可以返回预设值,比如false或者根据测试场景自定义 return false; } return Application.Current.Properties.ContainsKey("token"); }
之后业务代码里调用TokenExists()代替直接访问Properties,就能避免空引用错误。
个人最推荐方案1,不仅解决当前测试问题,还能让代码更易维护和扩展。
内容的提问来源于stack exchange,提问作者Deniz
相关产品推荐
相关产品推荐

