Clean Code Practices in Test Automation

Clean Code Practices in Test Automation

What Makes a Good Test?

A good test should be:

1. Readable – You should be able to quickly understand and debug it.

2. Fast – No one wants to wait eight hours for test results!

3. Independent – Tests should not depend on each other; they should be able to run on their own.

4. Repeatable – They should run consistently, no matter the environment.

5. Robust – A good test should survive small system changes without breaking.

Clean Code Principles

Now, let’s talk about some principles that have helped me clean up my code over the years.

1. Clear Precondition and Post-condition Separation

Your test should only focus on one thing. For instance, if your test is named “Rename Book,” it should only rename the book. Don’t include unrelated actions like creating or deleting a book in the same test. If your test fails while renaming, the cleanup step (like deleting) might not even run, and that can cause all sorts of problems later.

2. Avoid Code Duplication

Repetitive code is a common problem. If multiple tests have the same precondition (e.g., logging in), move that part into a common method or base class. That way, you’re not copying and pasting the same code everywhere. But be careful: putting too much in the base class can cause issues, especially if your tests run in parallel.

3. Tests Should Be Atomic

Each test should do one thing and one thing only. If you’re testing both renaming and deleting a book in the same test, you’re making your life harder. If the renaming fails, you’ll never know if the delete functionality is broken too. Split these into two separate tests so you can isolate the issue faster.

4. Don’t Rely on Test Order

Even if your tests seem to be working fine when run together, you should be able to run them independently too. Avoid relying on the order in which tests are run or having implicit dependencies between them. If one test fails, it shouldn’t prevent other tests from running or passing.

5. Use Soft Assertions

Soft assertions are useful when you want to check multiple things in a test without stopping at the first failure. For example, if you’re checking a webpage, you can verify all elements are present before failing the test. It’s especially helpful for UI tests where multiple elements could be missing, and you want to report everything.

6. Use Descriptive Assert Messages

When an assertion fails, it’s important to know why it failed. Always include a message that makes it clear what was being checked. Without it, you might end up scratching your head, wondering why the test failed and what was supposed to happen.

To view or add a comment, sign in

More articles by Ketan Sethi

Explore content categories