Python 我如何使用 unittest setUpClass 方法()?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4891671/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I use the unittest setUpClass method()?
提问by urschrei
I'm looking for some basic examples of the python 2.7 unittest setUpClass() method. I'm trying to test some class methods in my module, and I've gotten as far as:
我正在寻找 python 2.7 unittest setUpClass() 方法的一些基本示例。我试图在我的模块中测试一些类方法,我已经得到了:
import unittest
import sys
import mymodule
class BookTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls._mine = mymodule.myclass('test_file.txt', 'baz')
But I have no idea how to proceed from here to write tests utilising the object I just created.
但是我不知道如何从这里开始使用我刚刚创建的对象编写测试。
采纳答案by Sam Dolan
In your test methods you can now access the global class atribute _minethrough self. So you can do something like this:
在您的测试方法中,您现在可以_mine通过 self访问全局类属性。所以你可以做这样的事情:
def test_something(self):
self.assertEqual(self._mine.attribute, 'myAttribute')
回答by seddonym
If you're using Django 1.8+, you should use the setUpTestDatamethod instead.
如果您使用的是 Django 1.8+,则应改用该setUpTestData方法。
You can then set any attributes on the clsobject, and access them via the individual test methods on the selfobject.
然后,您可以在cls对象上设置任何属性,并通过对象上的各个测试方法访问它们self。
More information is in the Django docs.
更多信息在Django 文档中。

