单元测试:ResultPageViewModelTest
问题一:如何监控状态信息(Status)?
如何感应变化?利用mvvm每次status变化时,都会自动触发PropertyChanged事件这个事实。
每次发生变化时将status加入列表。
public class ResultPageViewModelTest {
/// <summary>
/// 测试诗词集合。
/// </summary>
/// <returns></returns>
[Test]
public async Task TestPoetryCollection() {
var poetryStorage =
await PoetryStorageHelper.GetInitializedPoetryStorage(); //获得一个初始化后的诗词存储
var resultPageViewModel = new ResultPageViewModel(poetryStorage); //获得ResultPageViewModel
resultPageViewModel.Where = Expression.Lambda<Func<Poetry, bool>>(
Expression.Constant(true),
Expression.Parameter(typeof(Poetry), "p")); //给出where条件:此where条件表示任何一首诗都满足条件
var statusList = new List<string>(); //需要监控状态信息变化,因为不停地变化,因此使用列表把所有状态都记录下来
resultPageViewModel.PropertyChanged += (sender, args) => { //当PropertyChanged被触发,则执行以下函数
if (args.PropertyName == nameof(ResultPageViewModel.Status)) {
statusList.Add(resultPageViewModel.Status);
} //如果发生变化的属性是Status,则将Status加入列表中
}; //如何感应变化?利用mvvm每次status变化时,都会自动触发PropertyChanged事件这个事实
Assert.AreEqual(0, resultPageViewModel.PoetryCollection.Count); //未加载时数据为0
await resultPageViewModel.PageAppearingCommandFunction(); //触发页面显示命令
Assert.AreEqual(20, resultPageViewModel.PoetryCollection.Count); //触发后数据加载为20
Assert.AreEqual(ResultPageViewModel.Loading, statusList[0]); //验证第0项(正在载入)
Assert.AreEqual(string.Empty, statusList[1]); //验证第1项(Empty)
//var poetryCollectionChanged = false; //poetryCollection有无变化
//resultPageViewModel.PoetryCollection.CollectionChanged +=
// (sender, args) => poetryCollectionChanged = true; //PoetryCollection每次发生变化时触发CollectionChanged
//await resultPageViewModel.PageAppearingCommandFunction(); //where条件没有任何变化,因此页面显示命令不应该有作用
//Assert.IsFalse(poetryCollectionChanged); //poetryCollection应该未改变
await resultPageViewModel.PoetryCollection.LoadMoreAsync();//加载数据
Assert.AreEqual(30,resultPageViewModel.PoetryCollection.Count);//因为数据库一共只有30条
Assert.IsFalse(resultPageViewModel.PoetryCollection.CanLoadMore); //不可再加载
Assert.AreEqual(5, statusList.Count);
Assert.AreEqual(ResultPageViewModel.Loading, statusList[2]);
Assert.AreEqual(string.Empty, statusList[3]);
Assert.AreEqual(ResultPageViewModel.NoMoreResult, statusList[4]);
//Assert.IsTrue(poetryCollectionChanged);
await poetryStorage.CloseAsync();
}
}