Best practices testing with TestNG

TestNG is a tool similar to JUnit for testing applications that provides extra functionalities. Let’s see some recommendations to use it better:

  • Define sets of tests (testSuites) in xml files. Doing so you can test only a part of the application, check minimal functionality (happy path), etc.
  • Separate unit tests (test a specific functionality) of integration ones (test the combination of many). This makes it easier to diagnose where the errors occur.
  • Use the description option and also document in the javadoc of each method the test steps and the expected results. Doing so it will be easier to fix it when it fails by a change in the application.
  • Write the data in xml or properties files instead of hardcoding them in Java code. Normally the data are repeated on multiple tests and if they change, you will only have to change them in one place.
  • Do not catch exceptions in tests: an exception should be thrown and thus abort the test if something fails.
  • Continuous Integration: is easy to configure your CI system to launch all tests every time a version is deployed or when the code is commited, so the errors will be detected as soon as possible. This will also give you the peace of mind that in the new version still works everything of the previous one.
  • Use the methods @before and @after to group the steps that should be executed at the beginning and end of all the methods of a class. This avoids code repetition and the changes will only be modified in one place.

Do you know other best practices? You can share them in the comments:

Rafael Borrego

Consultant and security champion specialised in Java, with experience in architecture and team management in both startups and big corporations.

Disclaimer: the posts are based on my own experience and may not reflect the views of my current or any previous employer

Facebook Twitter LinkedIn 

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>