Writing Unit tests - A Use Case
This FAQ explains when and how to write unit tests.Let us say that you have the following requirement. In http://sahitest.com/demo/training/login.htm, let us say that you wish to validate that
-
The
Username
field cannot take more than 50 Characters -
The
Password
takes only Alphanumeric characters that has to be more than 6 Characters.
info
In this case, writing multiple scripts for various validations is not the right approach. You would rather write multiple Test Cases in unit tests style to do all the validations.
Unit test cases can be written in a Sahi script as functions starting with test, example: testUserNameMax50Characters
.
Refer to
userdata\scripts\demo\clickCombo.sah
as an example of how to write unit tests in a Sahi script.
As regards your specific scenarios, you may have the following tests
-
testUserNameMax50Characters
- Set value in textbox with more than 50 characters.
- Get value from textbox and assert that its length is only 50 characters and it is equal to a substring of the set value containing the first 50 characters.
-
test1CharacterPassword
- Set 1 random alphanumeric character.
- Check that you get an alert that password has to be more than 6 characters.
-
test2CharacterPassword
- Set 2 random alphanumeric characters.
- Check that you get an alert that password has to be more than 6 characters.
You can similarly write -
testPasswordNonAlphaNumeric
- Pick a random length greater than 6.
- Pick a random index and set a random non alphanumeric character in that index. The rest of the characters can be random alpha numeric.
- Check that you get an alert that password can contain only alpha numeric characters
-
testPasswordAlphaNumeric
- Pick a random length greater than 6.
- Each character can be a random alpha numeric character.
- Check that the operation is allowed
test3CharacterPassword
, test4CharacterPassword
, test5CharacterPassword
, test6CharacterPassword
.
The tests can be run as follows.
- Use _runUnitTests() to run all tests.
- Pass an array of testcases in _runUnitTests() to run the specific set of testcases. Example: _runUnitTests(["testUserNameMax50Characters", "testPasswordAlphaNumeric"]) will run testUserNameMax50Characters and testPasswordAlphaNumeric.
userdata\scripts\demo\clickCombo.sah
is another example of how to write unit tests in a Sahi script, and how to call them.