What are the most effective ways to write test cases?
Learn from the community’s knowledge. Experts are adding insights into this AI-powered collaborative article, and you could too.
This is a new type of article that we started with the help of AI, and experts are taking it forward by sharing their thoughts directly into each section.
If you’d like to contribute, request an invite by liking or reacting to this article. Learn more
— The LinkedIn Team
Writing test cases is an essential skill for any programmer who wants to ensure the quality and functionality of their code. Test cases are scenarios that describe the expected input, output, and behavior of a program or a feature under specific conditions. They help developers to verify that their code meets the requirements, identify and fix bugs, and prevent future errors. But how can you write effective test cases that cover all the possible scenarios and are easy to maintain and execute? Here are some tips to help you.
Before you start writing test cases, you need to define the scope and purpose of your testing. What are the features or functionalities that you want to test? What are the acceptance criteria and the expected outcomes? What are the risks and assumptions involved? Having a clear and specific scope and purpose will help you to focus on the most important and relevant test cases and avoid wasting time and resources on unnecessary or redundant ones.
-
Mina Magdy
Senior Principal FPGA/ASIC/Firmware Design Engineer at Valeo
Testing is a skill and it is a type of art, and to write a testcase you need: 1- understand the user story. 2- define the inputs, output and Operation. 3- Start with the a very basic Positive Scenario and write its testcase. 4- Exploratory Testing will help you to understand how the full system is behaving. 5- Then start to Cover advanced scenarios (Boundary test, MCDC,....). 6- Then go for the interaction between different scenarios. 7- Start the automation of the test cases (self generated stimulus, self checking output, automated reporting and coverage collector). 8- Target the Negative Test Cases(for the scenarios that is not mentioned in the requirement). 9- Apply Random Testing, this will help increasing the coverage.
-
Hritik Khurana
Engineering @Edifecs | SIH'22 Winner | Google Dev Startup Class'22 | GDSC'21 Lead | I help companies build scalable web applications 📈
Writing effective test case usually involve considering the aspects like what the software needs to do, its performance, usability and most importantly the security. So It's very important to have clear understanding of the user stories and overall flow of the project that how it's actually working.
(edited) -
Sanjay Singh
Head of Software Engineering at Prudential Singapore
Scope and purpose is the key to write tests, and there are 3 key principles I follow: 1. Find out WHAT/WHY that triggered the code changes 2. Write down acceptance criteria that are related to your changes (ensure they are translated to automated tests then) 3. Find out scenarios where your code won’t work but it should (and when you fix that ,put test to validate it )
A test case should follow a standard format that includes the following elements: a unique identifier, a description, a precondition, a test data, a test step, an expected result, and a postcondition. A unique identifier helps to track and organize your test cases. A description summarizes the objective and the scenario of the test case. A precondition specifies the state or the condition that must be met before the test case can be executed. A test data provides the input values or parameters that are used in the test case. A test step describes the actions or operations that are performed in the test case. An expected result defines the output or the outcome that should be observed after the test step. A postcondition describes the state or the condition that should be achieved after the test case is executed. Following a standard format will help you to write clear, consistent, and comprehensive test cases that can be easily understood and executed by anyone.
-
Sam Cooper
Software Engineer
Setup, act, assert—I find this a useful three-step template to keep in mind for any test cases. Setup: get the system into the right state and prepare the inputs you need. Act: execute the code which you want to test. Assert: validate the outputs from the action, or the new state of the system. BDD-style tests follow the same pattern, using "given, when, then" instead. Given that the system is in this state, when I perform this action, then this should be the result. You don't have to be too strict, though. "One assertion per test" is a common rule, but it won't fit every real-life scenario. Use standards as a starting point, but prioritise clarity and readability over arbitrary rule-following.
-
Yakshup Goyal
Solution Architect | Solution Design | Supply Chain | Python | Cloud | DevOps | SCM | Cyber Security | ELK
There is a pretty standard format used by whole software community so far: 1. Setup 2. Execute 3. Assert 4. Tear down Each test case should be well documented and should also be in line with business requirements. Having additional test cases is never bad. But that only gets clarified with proper discussions among stakeholders. As a developer, people sometimes miss the business requirement which can be amended when talking about proper testing
-
Diego Ramirez
It is important to have appropriate structure but in my experience, it is more important to have a common language while writing the test. I am not referring to a programming language, but the wording while writing sentences for preconditions, actions and results. i.e. instead of using {press, push, pick, hit, etc.} the test should use only 1 word for all the scenarios.
A test case should use simple and precise language that avoids ambiguity and confusion. You should avoid using jargon, slang, or acronyms that may not be familiar to other testers or stakeholders. You should also avoid using vague or general terms that may have different interpretations or meanings. For example, instead of saying "check the performance of the program", you should say "measure the response time and the memory usage of the program". Using simple and precise language will help you to write accurate, unambiguous, and verifiable test cases that can be executed without errors or doubts.
-
Amit Kumar Gupta
Research Enthusiast Trusted by NASA, Microsoft, FDA, VMware and many
Long back I built a framework where you can mock HTTP based services in few seconds and just in 2 lines without any extra configuration so that QAs can focus on what they have to test. https://github.com/NaturalIntelligence/Stubmatic
-
Liam O'Donnell
Software Engineer • Sharing tech industry insights & Teaching you how to build software
A good way to vet out your test names is to ensure they answer two questions: 1. What is the action occurring 2. What is the expected result
-
Milan Parmar, PhD
Researcher @ Mississippi State University (Machine/Deep Learning - Python | MATLAB | R ) 📈
Write test cases in simple and clear language. Avoid jargon or ambiguity. Anyone should be able to understand and execute the test cases without confusion.
A test case should cover both positive and negative scenarios that may occur in your program or feature. A positive scenario is one that follows the normal or expected flow of the program or feature and produces the desired result. A negative scenario is one that deviates from the normal or expected flow of the program or feature and produces an error or an exception. For example, if you are testing a login feature, a positive scenario would be entering a valid username and password and accessing the account, while a negative scenario would be entering an invalid username or password and receiving an error message. Covering both positive and negative scenarios will help you to test the robustness and the reliability of your program or feature and ensure that it can handle different situations and inputs.
-
Varsha Prasad
Senior Software Engineer at Red Hat | CMU grad | GSoC Mentor | K8s enthusiast | STEM Advocate
While writing tests, the two major key aspects to remember are: 1. Covering Foreseeable Edge Cases: - Test extremes and invalid inputs to uncover potential issues. - Address boundary conditions, unexpected values, and edge cases. 2. Maximizing Code Path Coverage: - Test various input combinations to explore different code paths. - Ensure statements and branches are executed, and dead code is identified. By balancing these two aspects, we can create effective test cases that reveal both common and unexpected issues.
-
Aastha Saraf
SDE @Amazon | Python | Fullstack | Backend | AR/VR | GHC 23 | Afrotech 23
One thing I have found useful is to create a truth table that gives an understanding of how many different scenarios and combinations are to be tested specially in cases where you have multiple if else conditions
-
Avishek Majumder
Senior Data Scientist
- No need to write test cases for functions you’re not developing(external imported libraries) - Start with the most obvious cases, generally as you’re writing these cases, you can think of more nuanced ones - Any feature being developed should have test cases written even before the feature is defined (TDD) - Maintain order and hierarchy when writing test cases, as you might end up writing the same one more than once
A test case should be prioritized and categorized according to its importance, complexity, and frequency. Prioritizing your test cases will help you to decide which ones should be executed first and which ones can be deferred or skipped. Categorizing your test cases will help you to group them based on their functionality, module, type, or level. For example, you can categorize your test cases as unit, integration, system, or acceptance tests, or as functional, non-functional, or regression tests. Prioritizing and categorizing your test cases will help you to organize and manage your testing process and ensure that you cover the most critical and relevant aspects of your program or feature.
-
Mishu Lojan
Technology and Innovation Manager at TIPTI S.A
Prioriza los casos de prueba basándote en la importancia de la funcionalidad, la criticidad para el negocio, la frecuencia de uso y el riesgo asociado.
-
Rajat P.
Helping Entrepreneurs worldwide in building their Mobile Strategies.
Identify Critical Test Cases: Determine which test cases are critical to the core functionality or performance of the program or feature. Assign Priority Levels: Categorize test cases into priority levels such as high, medium, or low based on their importance and impact. Consider Complexity: Assess the complexity of each test case and prioritize accordingly. High-complexity cases may need more attention. Frequency of Use: Evaluate how frequently specific features or modules are used, prioritizing test cases related to frequently accessed functionalities. Categorize by Test Type: Group test cases by type, such as unit, integration, system, acceptance, functional, non-functional, or regression tests.
-
Waddah Alhasani
Packet Switch & Datacom Specialist at YOUtelecom
Some cases are related to others and some cases if tested will create other cases and will ignore some others this lead you to prioritize and categorize you cases.
A test case should be reviewed and updated regularly to ensure that it is still valid, relevant, and effective. You should review your test cases before and after each testing cycle to check if they are aligned with the requirements, the design, and the code of your program or feature. You should also update your test cases whenever there are changes or modifications in your program or feature that may affect its functionality, performance, or behavior. Reviewing and updating your test cases will help you to maintain the quality and the accuracy of your testing and avoid missing or outdated test cases that may lead to false results or errors.
-
Kunal Bhatnagar
Principal Technical Architect at Ust blueconch
The biggest mistake people usually make while writing test cases is to just care for coverage. Test cases are code which needs to be written in easy to understand and maintain. If you end up writing a test suite that is difficult to maintain/fix, it does not serve the purpose. Test cases needs to be designed just like the code under tests. Test cases giving false positive or tests breaking for no apparent reason or difficult to fix are signs of improperly designed tests.
-
Milan Parmar, PhD
Researcher @ Mississippi State University (Machine/Deep Learning - Python | MATLAB | R ) 📈
Regularly review and update your test cases as the software evolves. Ensure they remain accurate and relevant to the current state of the application. Collaboration with team members and stakeholders can help identify improvements.
-
Avishek Majumder
Senior Data Scientist
Follow the epic or user stories to update test cases first before making changes to the feature. This helps maintain a documented workflow for the features (both development and testing).
-
Massoud Beygi
Results-Driven Team Player | Continuous Learner
Writing tests should be a cultural practice within a team. When this culture has not matured within the organization, it is often just a perfunctory process that lacks the necessary attention to create effective tests. Ultimately, it turns into a time-consuming task where we only go through our own tests without creating any value, especially in enterprise products. Neglecting this aspect can lead to serious consequences. So, it is crucial to remember that for writing tests, the team must work together and cultivate the culture of effective testing.
-
Aslan Ali
Senior Software Engineer at ARM | Expertise in C, Python, and Computer Architecture
In case you have multiple versions of a software being shipped out to different customers, one may need to write different test case scenarios for different versions. Also if a higher version is backward compatible with the previous one, some tests should be created/ maintained that test this compatibility (and regularly revise the tests as well)
-
Sean Larkin
Chief Revenue Officer at Honeycom3 | Cloud, AI, Product Management
An additional aspect to consider occurs when large complex systems demonstrate emergent properties that are not evident when performing unit testing. Traditional testing assumes we know the properties of the system. Chaos engineering serves to inject known perturbations into the testing from a people perspective in several clever ways. Dave Rensin, Distinguished Engineer at Google has an exceptional talk you can find on YouTube that describes various techniques that can be injected to test the robustness of the triumvirate of people, processes & technology. Ultimately, this approach is used to understand the gap between how the system should behave and how it actually does behave.