在Django中的模拟测试在TestCase中全部运行时不工作,但是一个接一个地运行良好 [英] Mocking test in Django not working when running all in TestCase but works well one by one
问题描述
如果我独立运行每个测试,所有的测试都可以工作,我使用python mock来修补一些函数和类。但是当我运行TestCase时,一些测试不起作用(补丁没有效果)。
类ViewsTest(TestCase):
@ mock.patch('extras.utils.get_user_category')
def test_select_test(self,mock_method):
mock_method.return_value =类别(id = 1,name =Foo)
response = self.client.post(reverse('select_test',args = ['Foo']))
self.assertEqual(200,self.client.post(reverse ('select'))
@ mock.patch('user_profile.models.Profile.categories')
def test_category_view(self,mock_related):
mock_related。 all.return_value = []
self.assertEqual(200,self.client.post(reverse('category'))。status_code)
我有一个打印int的视图,看到每个嘲笑的方法,当它的作品打印:
MagicMock name ='get_user_category'id ='162815756'
什么时候不工作我看到:
函数get_user_category在0x8e0fb8c
我尝试了修补程序start()和stop(),但我仍然有问题。
¿什么问题?
我也有同样的问题。你可能指向错误的方式。
检查这个链接。它帮助我。
I'm using python mock for patching some functions and classes when testing views in Django.
If I run each test independently, all test works. But when I run the TestCase, some test dont work (the patch has not effect).
class ViewsTest(TestCase):
@mock.patch('extras.utils.get_user_category')
def test_select_test(self, mock_method):
mock_method.return_value = Category(id=1, name="Foo")
response = self.client.post(reverse('select_test', args=['Foo']))
self.assertEqual(200, self.client.post(reverse('select')).status_code)
@mock.patch('user_profile.models.Profile.categories')
def test_category_view(self, mock_related):
mock_related.all.return_value = []
self.assertEqual(200, self.client.post(reverse('category')).status_code)
I have a print int the views to see each mocked method, when it works it prints:
MagicMock name='get_user_category' id='162815756'
And when doesn't works I see:
function get_user_category at 0x8e0fb8c
I tried the patcher start() and stop() but I still have problems.
¿What is the problem?
I had the same problem. You're probably pointing the wrong way.
Check this link. It helped me.
这篇关于在Django中的模拟测试在TestCase中全部运行时不工作,但是一个接一个地运行良好的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!