200-901 Question 116
Single answerYou are developing a Python application that interacts with a RESTful API. To ensure your code properly handles the API responses, you need to test a function, parse_response(data), that processes JSON data returned from the API. Which of the following demonstrates proper usage of Python's unittest module to test the function?
- A
Define a test class that inherits from
unittest.TestCase, define test methods starting withtest_, and use assertions such asself.assertEqualto verify results. - B
Create a Python script that calls the
parse_responsefunction with sample data and prints the output for manual verification. - C
Write a test function starting with
test_and call assertions directly without using a test class. - D
Use the
unittest.main()function to automatically discover and run all test scripts in the project.
Show answer and explanation
Correct answer: A
Explanation
Unit tests in Python using the unittest module follow a specific structure: a test class derived from unittest.TestCase, test methods starting with test_, and assertions to validate expected outcomes. This ensures a standardized, automated, and maintainable testing process.
- A. Correct.
Correct: To construct a proper unit test in Python using the
unittestmodule, you need to define a class that inherits fromunittest.TestCase, write test methods prefixed withtest_, and use assertions to validate the behavior of the function being tested. - B. Incorrect.
Incorrect: While printing output for manual verification can help during debugging, it is not considered a proper unit testing approach as it lacks automation and integration with testing frameworks.
- C. Incorrect.
Incorrect: Test functions should be part of a test class when using the
unittestmodule. Writing standalone test functions is not aligned withunittest's structured approach. - D. Incorrect.
Incorrect:
unittest.main()is used to run the tests, but it does not replace the need for properly constructing test cases and test methods.