Introduction to Testing in Python
Sveip for å vise menyen
Testing is a fundamental practice in software development, ensuring that your code behaves as expected and remains reliable as it evolves. Automated testing allows you to check your code automatically, rather than relying on manual checks that are time-consuming and error-prone. By writing tests, you can quickly detect when changes break existing functionality and confidently refactor or extend your code.
One of the most popular approaches to testing is test-driven development (TDD). In TDD, you begin by writing a test that describes a desired behavior or feature before you write the code to implement it. This process encourages you to think carefully about requirements and edge cases upfront, leading to cleaner and more maintainable code. After writing the test, you implement the minimal code required to pass the test, and then you refactor the code for clarity or efficiency, running the tests again to ensure nothing breaks. This cycle - write a test, write the code, refactor - helps you build robust software incrementally.
Testing is not just about catching bugs. It also serves as living documentation for your code, making it easier for others (and your future self) to understand how your code is supposed to work. Automated tests are especially valuable when collaborating in teams or working on large projects, as they provide a safety net that encourages experimentation and confident code changes.
12345# A function to add two numbers def add(a, b): return a + b print(add(2, 3))
# A basic test case for the add function using unittest
import unittest
class TestAddFunction(unittest.TestCase):
def test_add_positive_numbers(self):
self.assertEqual(add(2, 3), 5)
def test_add_zero(self):
self.assertEqual(add(0, 5), 5)
def test_add_negative_numbers(self):
self.assertEqual(add(-1, -1), -2)
The provided code defines a test case class named TestAddFunction using Python's built-in unittest framework. Inside this class, you find three test methods:
test_add_positive_numberschecks that callingadd(2, 3)returns5;test_add_zeroverifies that adding zero and five withadd(0, 5)returns5;test_add_negative_numbersconfirms that adding two negative numbers,add(-1, -1), returns-2.
Each test method uses self.assertEqual to compare the actual result of the add function with the expected value. If any test fails, the framework will report it, helping you catch mistakes early.
Takk for tilbakemeldingene dine!
Spør AI
Spør AI
Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår