200-901 Question 117
Single answerYou are tasked with testing a Python function called calculate_sum(a, b), which takes two integers and returns their sum. Using the unittest library, you write the following test case:
import unittest
from my_module import calculate_sum
class TestCalculateSum(unittest.TestCase):
def test_sum(self):
result = calculate_sum(3, 5)
self.assertEqual(result, 8)
What must you do next to ensure this test case runs correctly?
- A
Include a
if __name__ == "__main__": unittest.main()block in the script. - B
Change
self.assertEqual(result, 8)toassert result == 8. - C
Move the
calculate_sumfunction definition inside the test class. - D
Rename the
test_summethod torun_sum.
Show answer and explanation
Correct answer: A
Explanation
To ensure that the test case executes properly in the unittest framework, you need to include a if __name__ == "__main__": unittest.main() block in the script. This ensures that the test runner executes all defined test cases in the script when it is run directly. Other options either break unittest conventions or do not align with proper Python testing practices.
- A. Correct.
This is the correct way to execute the unit tests when using the unittest framework. The
unittest.main()method discovers and runs all test cases in the script. - B. Incorrect.
This is incorrect. While
assertcan be used for basic assertions, it does not integrate with the unittest framework and will not produce detailed test results. - C. Incorrect.
This is incorrect because the
calculate_sumfunction should remain in its own module (my_module) for proper modularity and testing. - D. Incorrect.
This is incorrect because unittest automatically discovers methods starting with
test_. Renaming the method torun_sumwill prevent it from being executed as a test case.