Test Automation scripts can turn into a night mare if not written and maintained in an efficient way. If we take care of something small now, it can eliminate bigger problems later. This article offers tips (organized into categories) for writing Automation code which has fewer bugs, is more easily maintained, and takes advantage of some of the most powerful features of Object Oriented approach.
1. Considerations for Page Elements
Identification of page elements & structuring them effectively is the most important task when you start scripting. While handling page elements, keep these things in mind:
- Define page elements separately either in a separate class or at the top of the class to keep them isolated from implementation details. As a result, when you have to make a change, you’ll make it in one place only and the effects will be felt immediately throughout the code. It will result in highly maintainable & readable code. While developing Selenium WebDriver tests, you can consider using the Page Object model pattern. Page Object Model is a design pattern to create Object Repository for web UI elements. In this model, for each web page in the application there should be corresponding page class.
- Locate page elements by using locators in below order:
- Element’s ID
- Element’s name attribute
- CSS Selector
- XPath statement
- Links text
- Document object model (DOM)
- Using an element ID or name locator is the most efficient way in terms of test performance, and also makes your test code more readable; assuming the ID or name within the page source is well-named.
- After ID & Name, CSS selector is the best possible way to locate complex elements on the page. This is useful for locating items that have a unique style. CSS Selectors are faster than XPath. CSS will not change based on browsers that is it will behave same in all browsers.
- XPath statements take longer to process. Also XPath will behave differently in IE browser.
- Link text is a good option to use if there are links present on the page that are not likely to change or they are dynamically generated while using some pattern.
- DOM locators are no longer commonly used since XPath provides all functionality what DOM can do. DOM locators are available simply to support legacy tests.
2. Modular Code
- Create Common Module Class to hold common functions.
- Structure your code using local methods/functions to reduce code volume and improve readability. It will reduce the size of the class/module by stripping it of repetitive code. Even if you do not repeat sections of code within a module, you still may want to pull out a set of related statements and package them into a local module to make it easier to follow the logic. It will also be less prone to error as there won’t be complex structures resulting in confusion.
- If to explain what a method does makes its name too long to deal with, the method is not focused enough, and should be refactored into smaller units.
- Use consistent indentation to reflect the logical structure of your program.
3. File & URL Paths
Use relative locations for files and urls in the script if needed. Avoid absolute paths. Using absolute paths in code leads to runtime issues when others want to execute the same code on a different machine.
4. Data Handling
To avoid getting burned by literals which have been littered throughout your code, follow these guidelines:
- Remove all literals from your code. Instead, declare variables which hold those literal values.
- Create your own mechanism of handling data. Avoid any data hard coding at script level.
5. Object Naming Convention
A name can make a big difference in the usability of your variables, modules and parameters. Your names should improve the self-documenting nature of your code.
- Use a standard way to name your objects & variables. It will result in a maintainable code.
The “Code Conventions for the Java Programming Language” followed and recommended by Sun can be used as the foundation for the development standards. Details can be found at http://www.oracle.com/technetwork/java/codeconvtoc-136057.html.
- While naming classes & methods, make it readable and understandable. Don’t try to make it small or with few characters. Class names and function names should be explicit enough to explain what is going on.
Whichever approach you take, make sure it aids in readability — and use it consistently
6. Keyword Structure Planning
If you are using keyword driven framework, spend some time planning the keyword structure and this additional time will pay you off while you start coding.
- Decide some basic principle to name the keywords in Keyword Driven Testing.
- Decide on vocabulary and phrases – In fact one of your first tasks should be to decide on the Verbs you want to handle in your application and your domain.
7. Debugging Code
While inserting debugging code into your script, insert meaningful text to track the values of variables and to identify your location in code.
Avoid static waits, instead use the Dynamic Wait approach.
9. Use of Proper Comments
Always use proper comments while writing code. Other than increasing the readability, it also provides one important side benefit. In order to comment something, you have to understand it first. When you trying to comment a function, you are actually thinking of what the method/function/class does, and this makes you be more specific and clear in your design, which in turn makes you write more clear and concise code.
Comments often save time and effort when designer comes back to a project months later.
What should be commented?
- Provide proper details about variables being used.
- APIs, framework classes, and internal reusable static methods should be commented thoroughly.
- Add comments to every if statement especially for nested If’s to make it easily understandable and manageable.
- Logic in every complicated piece of code should be explained on two places – general logic in javadoc, and logic for each meaningful part of code in it’s own comment.
- If page has complex design, you can divide related code into different sections with proper comments to make it more readable, for example “Business details starts here”.
What shouldn’t be commented?
- Don’t comment getters, setters, or anything done “by the book”. If the team has a standard way of creating elements you don’t need to document them. Anyone familiar with framework will know what they’re for – assuming that the framework philosophy and way of working with it is documented somewhere. In such cases, comments mean additional clutter and have no purpose.
In short, comment logic, not syntax, and do it only once, on a proper place.
When to use Javadoc comments?
People usually avoid Javadoc comments but when you are writing javadoc comments using an IDE like eclipse or NetBeans, it isn’t that troublesome and will provide many benefits:
- Use Javadoc for every method that somebody else can use (any public method) at least stating its obvious purpose.
- Consider to add Javadoc comments to every protected method in every API class, though to a lesser extent. This goes on the idea that any developer who is extending an API class will get a fair concept of what’s going on.
- Also document private and package private methods for your own benefit. Any method or field that you think needs some explanation in its usage will receive documentation, regardless of its visibility. Even though that documentation will not be visible in the javadoc API files, still it allows you to remember more easily the precise nature of the different steps of your complex algorithm. As Javadoc comments are recognized by IDE so it will help you by displaying a help pop-up when you move your cursor on top of your – javadoc-ed – function.
- You can also run javadoc against code that does not have javadoc comments and it will still produce fairly useable javadocs if you have given thoughtful names to your methods and parameters.
10. Review your code
- Get someone to review your code and in return you can review their code…Peer review is very important to improve your code. Also perform self-review of your code to improve code quality.
- Develop a strategy to review code in chunks alongside new feature development. Fixing issues in earlier stages is less costly than waiting for an ideal time when all development will be completed and you’ll have enough time to improve your code…That ideal time usually never comes as you’ll be busy with new project.
A great programmer loves to look at his or her own code and go through it…. Greatness is the notion of always wanting to simplify, always thinking you can make it better, and really loving to look at your own code…. There are some people who, once a thing works, won’t go back and look at it— that’s a crummy programmer.
While reviewing your software code, keep in mind to check following coding problems:
- Not following standard
- Not keeping performance in mind
- History, Indentation, Comments are not appropriate.
- Readability is poor
- Too much hard coding.
- Poor error handling.
- No modularity.
- Repeated code.
You should always accept review comments happily and should be thankful to your code reviewers about the comments as he/she is helping you improve.
11. Recommendations for Candidate Test Cases for Automation
- Neither group test case steps too close, nor wide to be able to determine test case complexity and required effort accurately. Be aware that the pre-script development effort for each test script is considerable as the following activities are time-consuming operations:-
1) Executing test case manually before scripting for confirming the successful operation.
2) Test data selection and/or generation for the script.
3) Script template creation (like header information, comments for steps, identifying the right reusable to be used from the repository and so on.)
These efforts are highly based on the number of steps in the test case. Note that if test case varies by fewer steps, then this effort does not deviate much but in case it varies by many steps even this effort widely differs.12. Documentation
Documentation is the Key to become successful software developer, tester or architect. If necessary documentation is present for reference, it will save lots of time that is otherwise spent in figuring out what should be done if certain situation occurs. Here is a list of documents that can be created during project life cycle and can be referenced back when needed.
- Design Approaches
- Tips and Tricks
- Special functions, commands and instructions
- Lessons learnt
- Debugging methods
- Best Practices
- Anything which can help you in future
13. Back-up your documents
Make a habit of taking daily backup of your artifacts, especially those documents that are not being tracked through version control system.
14. Make notes of your commonly used commands
Note down commonly used commands and methods and keep them handy so that they can be used anytime without doing any R&D and save your valuable time. Better to maintain a text file having all such frequently used commands or you can use Microsoft OneNote to keep track of commonly used code
15. Use informative message while creating Test execution report
Execution report is generated after execution of a scenario. This report should include accurate and concise text messages to inform what steps were performed and what the result was. Take snapshots for every important step/screen.
16. Design End to End scenario before beginning test scripting
Consider writing one or two end-to-end and or integration tests before starting on new test scripts. The end to end scenario will act like a template scenario and will provide you a framework to cover many test scenarios.
17. Unit Test your test
Automation code is the code that changes often. When you are writing new test scripts, you’ll modify existing methods to accommodate the new features that all fall under same functional area. It makes it important to unit test your automation code just like developers write unit test to test their code. Including unit test with test automation code will allow you to verify that your test scripts still work after you make changes in test scripts.
18. Do it right the first time
Usually while starting, human’s impatient nature comes to play and they want to just jump in and start coding. Hold yourself back! Do the analysis up front so that you understand the requirements fully. Think through the implementation approach you will take. Uncover the pitfalls before you start coding. Analyze the problem and design a solution you can prove will solve the difficulty. You will always end up being more productive if you take the time to do it right the first time around.
19. Educate the team about best practices
Often people think we don’t have enough time to follow best practices in our code. It will slow down our actual task. That’s not true. Once you start using best practices it becomes your second nature.
Document, promote and encourage good practices that are more likely to be followed. Having lunch and learn sessions is a good idea.
20. Continuous Learning
Never think that you know enough and get stuck in your daily routine. Find some time to keep learning new concepts & emerging technologies. The new skills you’ll learn will help you think more objectively and write effective automation scripts. Few ideas for you to practice continuous learning…
- Visit websites about Test Automation.
- Explore open source test automation frameworks present in the market.
- Improve your programming skills. It would empower you to do many things you wouldn’t otherwise be able to do.
- Learn about Test Driven Development approaches like BDD, TDD, ATDD and how you can use it to write better test scripts.
- Learn about Agile Software Development, Principles, patterns and Practices.