如何创建unittest测试类的实例?

时间:2015-02-17 12:32:08

标签: python unit-testing

我正在尝试创建unittest TestCase的一个实例,以便我可以使用该类的变量和方法,但它给我一个错误:

In [1]: import tests

In [2]: obj = tests.TestDailyAggregations()
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-2-6a5e2091c8a1> in <module>()
----> 1 obj = tests.TestDailyAggregations()

/usr/lib/python2.7/unittest/case.py in __init__(self, methodName)
    187         except AttributeError:
    188             raise ValueError("no such test method in %s: %s" %
--> 189                   (self.__class__, methodName))
    190         self._testMethodDoc = testMethod.__doc__
    191         self._cleanups = []

ValueError: no such test method in <class 'tests.TestDailyAggregations'>: runTest

以下是我的tests.py文件,我想在其中创建TestDailyAggregations的一个实例并在TestWeeklyAggregations中使用它的变量user_daily_dict:

import unittest
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "rest_apis.settings")


    class TestDailyAggregations(unittest.TestCase):

        def test_daily_aggregation(self):

            ......

            daily = daily_aggregations
            user_daily_dict = daily.generate_aggregations_dictionary(user_workouts)

            date_list = self.get_dates(user_daily_dict)
            unique = self.check_unique_date(date_list)
            self.assertEqual(unique, True)

            total = self.check_total(user_daily_dict, user_workouts)
            self.assertEqual(total, True)

        def generate_mock_workouts(self, start_time, end_time):
            f......

        def get_dates(self, user_daily_dict):
            ......

        def check_unique_date(self, date_list):
            ......

        def check_total(self, user_daily_dict, user_workouts):
            ......

        def check_sum(self, user_daily_dict, user_workouts, calculate):
            ......

    class TestWeeklyAggregations(unittest.TestCase):

        def test_weekly_aggregations(self):
            obj = TestDailyAggregations
            user_daily_dict = obj.test_daily_aggregation(obj).user_daily_dict

            w = weekly_aggregations
            user_weekly_dict = w.generate_aggregations_dictionary(user_daily_dict)


    if __name__ == "__main__":
        unittest.TextTestRunner().run(TestDailyAggregations())

我该怎样做才能制作实例?

1 个答案:

答案 0 :(得分:0)

您只需通过传递它包含的methodName(例如onCreate())来实例化它。以下是setUp类的代码,如您所见:

TestCase

实例化后,您可以访问它包含的方法。 (我经常用这个技巧调试我的单元测试......)