昨天介绍了如何创建一个简单的CodedUI Test。我们也知道,依靠录制回放产生的自动化测试是非常不可靠的,那些在微软的大牛们肯定也早就知道了。虽然用VSTS录制一个自动化测试脚本的过程不是那么友好,也不是很方便,不过它产生的测试代码修改起来还是比较容易的。下面我们就看看如何把一个简单的CodedUI Test改造为数据驱动脚本。
对于每一段录制的操作,VSTS都可以把它抽象成一个方法,它会把这些操作以静态方法的形式存放在一个叫RecordedMethods的类里面。可以对这些方法做任意的修改,我就把给需要输入的方法增加一个输入的参数。
public class RecordedMethods { public static void FirstClick(TestContext testContext, string first) { //第一个输入 } public static void Operation(TestContext testContext, string operater) { //操作符 } public static void SecordClick(TestContext testContext, string second) { //第二个输入 } public static void GetResult(TestContext testContext) { //按那个等于号 } }
这些方法其实是怎么工作的呢?
public static void Click(TestContext testContext, string first) { // Click '1' button WinWindow 计算器Window = new WinWindow(); #region Search Criteria 计算器Window.SearchProperties.Add("Name", "计算器", "ClassName", "SciCalc"); #endregion WinWindow item1Window = new WinWindow(计算器Window); #region Search Criteria item1Window.SearchProperties.Add("ControlId", "125"); #endregion WinButton item1Button = new WinButton(item1Window); #region Search Criteria item1Button.SearchProperties.Add("Name", first); #endregion Mouse.Click(item1Button, new Point(7, 12)); }
首先是创建一个WinWindow对象,这个WinWindow类最终是继承自UITestControl类,这个类在Microsoft.VisualStudio.TestTools.UITesting.dll,是VSTS2010新引入的。程序首先找到计算器这个窗口,然后在计数器窗口上面找到输入的控件,然后在输入的控件上找到具体点击的按钮。这里我只需要对最后的一个搜索的条件进行参数化就可以了。
下面就是要准备一些数据作为输入:
1 + 1 2 0 - 0 0 3 * 3 9
通过向该CodedUI Test添加数据源,实现简单的数据驱动。
完成后的代码如下
public void AddOperationTest() { // From the context menu, select "Edit CodedUITest" and choose any of options to add automation code. RecordedMethods.Click(this.TestContext, TestContext.DataRow["First"].ToString()); RecordedMethods.Click(this.TestContext, TestContext.DataRow["Operator"].ToString()); RecordedMethods.Click(this.TestContext, TestContext.DataRow["Last"].ToString()); RecordedMethods.GetResult(this.TestContext); // Validate UIItemEdit.Text AreEqual 'xxx. ' Assert.AreEqual(TestContext.DataRow["Expected"].ToString()+". ", UIMap.UI计算器Window.UIItemWindow.UIItemEdit.Text); }
体会:VSTS自动生成的那个RecordedMethods类,里面的方法都是可以重用的,稍加修改,就能达到比较好的效果,同时也需要对这个类的方法进行清理。例如在本文中,RecordedMethods类中总共有4个方法,其中的三个方法FirstClick,Operation,SecordClick,它们其实都是一样的,就是点击计数器上的某个按钮,所以说这3个方法可以统一为一个方法Click。
微软一直以来所提供的傻瓜式的数据驱动的支持,很好地帮助我们实现数据驱动,有利于把测试脚本的编写与测试的设计分离。这一点如果有安装了TFS以后就能体验到,CodedUI Test可以与某个测试用例关联起来,公用数据。
如果大家对CodedUI Test很感兴趣,推荐大家看这个人(Mathew Aniyan)的博客,满城尽带CodedUI Test。