说实话,SilkTest对面向对象的支持远没有C++和Java那么强大。只能说silktest实现了基本的类的定义,继承,覆盖。其他很多高级的面向对象的机制,例如重载,silktest都无法实现,所以用4Test写一些类层次结构的时候可能会遇到困难。实践证明,尽量减少类的继承层数可以有效减少错误的发生的几率。
其实silktest的面向对象机制只有两个重要的关键字,一个是winclass,它是用来定义类的,相当于其他高级语言的class。另外一个是window,它用来定义一个某类的对象。下面是一个例子,定义了一个People类,并且定义了一个People类的对象worker
winclass People
window People work
看上去很简单是吧,好,下面大家可以看看下面的例子。在include文件People.inc中,定义了一个基类People,和它的一个子类Student。基类定义了两个成员变量分别是name和age,并且有相应的成员函数来set和get成员变量。子类Student另外定义了一个成员变量sex,相应地也有成员函数来set和get该变量。初次以外,Student还定义了两个函数来对该类的对象进行赋值和取值。在另外一个文件TestStudent.t中,声明了三个Student对象stu1,stu2, stu3,对他们进行一系列的赋值和取值操作,然后打印出对象的值,希望这个例子对你理解silktest中类的继承和对象的使用有所帮助。
[ ] //FileName: People.inc
[ ] //Author: Yuetian Zeng from http://blog.csdn.net/yuetian/
[ ]
[ ]
[ ] // base class
[-] winclass People
[ ] // declare two data members and set default value for them
[ ] string sName = “SilkTest”
[ ] int iAge = 10
[ ]
[ ] // set and get Age
[-] void setAge(int age)
[ ] iAge = age
[-] int getAge()
[ ] return iAge
[ ] // set and get Name
[-] void setName(string name)
[ ] sName = name
[-] string getName()
[ ] return sName
[ ]
[ ] // class Student inherit from People
[-] winclass Student: People
[ ] // declare a new data member and set default value for it
[ ] string sSex = “Male”
[ ] // set and get Sex
[-] void setSex(string sex)
[ ] sSex = sex
[-] string getSex()
[ ] return sSex
[ ]
[ ] // set and get instance
[-] void setStudent(Window s)
[ ] this.iAge = s.iAge
[ ] this.sName = s.sName
[ ] this.sSex = s.sSex
[ ]
[-] void getStudent( window s)
[ ] s.iAge = this.iAge
[ ] s.sName = this.sName
[ ] s.sSex = this.sSex
[-] void printInfo()
[ ] print(“{sSex} student {sName} is {iAge} years old”)
[ ]
[ ] //FileName: TestStudent.t
[ ] //Author: Yuetian Zeng from http://blog.csdn.net/yuetian/
[ ]
[ ] use “People.inc”
[ ] // declare 3 Student object
[ ] window Student stu1
[ ] window Student stu2
[ ] window Student stu3
[ ]
[ ]
[-] testcase TestStudent()
[ ] // initialize stu1
[ ] stu1.setName(“Mike”)
[ ] stu1.setAge(18)
[ ] stu1.setSex(“Male”)
[ ] // print stu1 data members
[ ] print (stu1.iAge)
[ ] print(stu1.sName)
[ ] print(stu1.sSex)
[ ] print(“————————“)
[ ]
[ ] // initialize stu2
[ ] stu2.setStudent(stu1)
[ ] // pirnt stu2 data members
[ ] print (stu2.getAge())
[ ] print(stu2.getName())
[ ] print(stu2.getSex())
[ ] print(“————————“)
[ ]
[ ] // change stu2
[ ] stu2.iAge = 20
[ ] stu2.sName = “Jane”
[ ] stu2.sSex = “Female”
[ ]
[ ] // initialize stu3 from stu2
[ ] stu2.getStudent(stu3)
[ ] // pirnt stu3 data members
[ ] stu3.printInfo()
接下来是我的电脑上的运行结果
[-] Testcase TestStudent – Passed
[ ] *** DefaultBaseState is setting TestApplication active, No window was active
[ ] 18
[ ] Mike
[ ] Male
[ ] ————————
[ ] 18
[ ] Mike
[ ] Male
[ ] ————————
[ ] Female student Jane is 20 years old