新浪微博客户端围脖七开发笔记(1) TDD环境的搭建
既然要用MVVM和TDD,两样利器必不可少:
2. Silverlight Unit Testing Framework
都有相应的WP7版本,添加dll到项目中即可。
下面大概说下要点:
1. 创建一个新项目WeiBo7
2. 添加一个测试项目WeiBo7.Test
1)添加 Microsoft.Silverlight.Testing & Microsoft.VisualStudio.QualityTools.UnitTesting.Silverlight到项目reference中
2)修改MainPage()如下
代码
// Constructor
public MainPage()
{
InitializeComponent();
// set up unit testing
Content = UnitTestSystem.CreateTestPage();
IMobileTestPage imtp = Content as IMobileTestPage;
if (imtp != null)
{
BackKeyPress += (x, xe) => xe.Cancel = imtp.NavigateBack();
}
}
3)创建一个新类MainViewModelTests
代码
using System;
using System.Net;
using Microsoft.Silverlight.Testing;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using WeiBo7.ViewModels;
namespace WeiBo7.Test
{
[TestClass]
public class MainViewModelTests : SilverlightTest
{
}
}
4)添加一个新的测试方法
代码
[TestMethod]
public void IsHomeRefreshing_SetValue_RaisesPropertyChanged()
{
var mainViewModel = new MainViewModel();
bool propChanged = false;
mainViewModel.PropertyChanged +=
(s, e) =>
{
if (e.PropertyName == "IsHomeRefreshing")
{
propChanged = true;
}
};
mainViewModel.IsHomeRefreshing = !mainViewModel.IsHomeRefreshing;
Assert.IsTrue(propChanged);
}
3. 添加一个ViewModelBase类,所有的viewmodel都要从它继承
代码
using System.ComponentModel;
namespace WeiBo7.ViewModels
{
public class ViewModelBase
{
protected void OnNotifyPropertyChanged(string p)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(p));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
}
4. 在WeiBo7中添加MainViewModel类并加入一个属性IsHomeRefreshing, 这是用来绑定ProgressBar的,目前UI还没创建,但已经可以测试它了!
代码
private bool _isHomeRefreshing = false;
/// <summary>
/// Indicates whether there is an indeterminate operation in progress
/// </summary>
public bool IsHomeRefreshing
{
get { return _isHomeRefreshing; }
set
{
if (value != _isHomeRefreshing)
{
_isHomeRefreshing = value;
OnNotifyPropertyChanged("IsHomeRefreshing");
}
}
}
如果没什么问题的话,运行测试项目,你会看到如下结果:
更详细的结果: