Skip to content
Get Free Trial

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 https://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.

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

    1. Set value in textbox with more than 50 characters.
    2. 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

    1. Set 1 random alphanumeric character.
    2. Check that you get an alert that password has to be more than 6 characters.
  • test2CharacterPassword

    1. Set 2 random alphanumeric characters.
    2. Check that you get an alert that password has to be more than 6 characters.

    You can similarly write test3CharacterPassword, test4CharacterPassword, test5CharacterPassword, test6CharacterPassword.

  • testPasswordNonAlphaNumeric

    1. Pick a random length greater than 6.
    2. Pick a random index and set a random non alphanumeric character in that index. The rest of the characters can be random alpha numeric.
    3. Check that you get an alert that password can contain only alpha numeric characters
  • testPasswordAlphaNumeric

    1. Pick a random length greater than 6.
    2. Each character can be a random alpha numeric character.
    3. Check that the operation is allowed

In general, you would write extensive unit tests that cover all scenarios and put it inside one script.

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.