Awesum Stuff

How to Use Classes in VBScript

Is VBScript Object Oriented ? NO. Its Object Based

Can we create Classes in VBScript ? YES

Is there a need to use Classes in VBScript ? You can manage well without using classes BUT you can use it to write efficient and robust code

Example of where we can use classes :-

Suppose we have Database reporting in our QTP Script and we use it to store the test results in our Database. Suppose, the script stops in between due to any unforeseen circumstances(with QTP i’m sure there’ll be lots of those), then the Database might be left with an orphan record with incomplete details. This is where we can use a Destructor to update the database. In the same class, we can use the Constructor to execute some code we need to execute when an instance of the class is created. In this example, I’m launching an application(called caffeine) that prevents the system from getting locked.

<<Code Starts>>

Class myScriptHandler

‘Constructor for this class

Public sub class_initialize

‘Start Caffeine Process
SystemUtil.Run Environment.Value(“TestDir”)&”\Input_Files\caffeine.exe”

End sub

‘Destructor for this class

Public sub class_terminate()

‘Stop Caffeine Process

Set l_wshShell = CreateObject(“Wscript.Shell”)
l_wshShell.Run(“cmd.exe /c taskkill /im caffeine.exe /f”)
Set l_wshShell = Nothing
‘Update Testexecution Table
Call DB_UpdateTE(TC_Executed_copy, TC_Passed_copy, TC_Failed_copy, Execution_ID_copy)

End Sub

End Class

<<Code Ends>>

So at the beginning of the Script, we need to write the following line :-

<<Code Starts>>

Set myObj= new myScriptHandler

<<Code Ends>>

This will invoke the constructor when this line is executed and the destructor will be invoked when the object is destroyed (this may happen when the script gets finished or stopped midway)

Please note : You will not be able to access any Global variables(declared in Library Files) inside the class.

Hope you found this post helpful. Happy Automating !

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s