Most of the Selenium automation projects use a unit testing library such as jUnit or Test NG.
A unit testing library is needed so that automated tests
can be created as unit tests
can be organized in test classes
can be executed easily
can have the automation environment set up and cleared up
What this means is that Selenium tests are unit tests.
OK, not unit tests that test that code works but unit tests that test that a website works.
Selenium tests are a special type of unit test.
Now that we clarified that, since Selenium tests are unit tests, what does this mean?
How should they look like?
What attributes should they have?
What rules should they follow?
This article from the Microsoft blog clarifies everything about unit tests (and Selenium tests).
1. What are the characteristics of a unit test (Selenium test)?
Fast
Isolated
Repeatable
Self-Checking
Timely
There are 2 differences here between unit tests and Selenium tests:
if unit tests are supposed to be very fast, Selenium tests are supposed to be slow
a unit test should not take longer to be created than the code that it tests; similarly, a Selenium test should not take longer to be executed than the test case that it implements
2. Arranging your tests
Use the Arrange, Act, Assert pattern:
Arrange your objects, create and set them up as necessary.
Act on an object.
Assert that something is as expected.
What does this mean for Selenium tests?
Arrange your environment and test data.
Act on the site in the browser.
Assert that the site works as expected.
In this order:
Arrange
Act
Assert
Also, keep these separated.
No test data setup if possible in the Act phase.
3. Write minimally passing tests
The input to be used in a unit test should be the simplest possible in order to verify the behavior that you're currently testing.
For Selenium tests, this means focusing on testing 1 single thing in a test.
4. Avoid logic in tests
When writing your unit tests, avoid manual string concatenation, logical conditions, such as if
, while
, for
, and switch
, and other conditions.
Do this as well for Selenium tests.
Only use page objects, page methods and assertions.
5. Avoid magic strings
Naming variables in unit tests is important, if not more important, than naming variables in production code. Unit tests shouldn't contain magic strings.
Read the whole article as there are many other good things in it.
Thanks for reading.