unittest.main()在main()中不起作用

时间:2018-11-08 06:30:12

标签: python

我正在课堂上学习unittest,遇到unittest.main()无法在main函数内运行的问题:

这里是class AnonymousSurvey,它收集调查问题的匿名答案。

import unittest

class AnonymousSurvey:
    """Collect anonymous answers to a survey question."""

    def __init__(self, question):
        self.question = question
        self.responses = []

    def show_question(self):
        print(question)

    def store_response(self, new_response):
        self.responses.append(new_response) 

    def show_results(self):
        print("Survey results:")
        for response in self.responses: 
            print("- " + response)

单元测试封装在main()函数中。

def main():

    class TestAnonymousSurvey(unittest.TestCase):
        """Test that a single response is stored properly"""

        def test_store_single_response(self):
            question = "What language did you first learn to speak?"
            my_survey = AnonymousSurvey(question)
            my_survey.store_response("English")

            self.assertIn("English", my_survey.responses)

    unittest.main()



if __name__ == "__main__":
    main()

它报告了ran0个测试

In [64]: !python survey.py                                                                                        

----------------------------------------------------------------------
Ran 0 tests in 0.000s

OK

我如何使其在main()区域中工作?

1 个答案:

答案 0 :(得分:2)

unittest's basic example一样,您只需将unittest.main()放入if __name__ == "__main__": if语句中,将unittest类留在外面。因此,您的单元测试代码应变为:

class TestAnonymousSurvey(unittest.TestCase):
    """Test that a single response is stored properly"""

    def test_store_single_response(self):
        question = "What language did you first learn to speak?"
        my_survey = AnonymousSurvey(question)
        my_survey.store_response("English")

        self.assertIn("English", my_survey.responses)

if __name__ == "__main__":
    unittest.main()