Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为什么';使用模拟对象的Python/Django单元测试是否有效?_Python_Django_Unit Testing_Mocking - Fatal编程技术网

为什么';使用模拟对象的Python/Django单元测试是否有效?

为什么';使用模拟对象的Python/Django单元测试是否有效?,python,django,unit-testing,mocking,Python,Django,Unit Testing,Mocking,我在理解如何编写Python3单元测试时遇到了困难,该测试使用模拟对象来模拟Django模型的实例方法。以下是我的模型和测试: # models.py class Author(models.Model): name = models.CharField(max_length=50) class Book(models.Model): title = models.CharField(max_length=100) author = models.ForeignKey(

我在理解如何编写Python3单元测试时遇到了困难,该测试使用模拟对象来模拟Django模型的实例方法。以下是我的模型和测试:

# models.py
class Author(models.Model):
    name = models.CharField(max_length=50)

class Book(models.Model):
    title = models.CharField(max_length=100)
    author = models.ForeignKey(Author, related_name='books')

    def retrieve_isbn(self):
        return 'abc123'

# tests.py
class TestModel(unittest.TestCase):
    @mock.patch('run.models.Book', autospec=True)
    @mock.patch('run.models.Author', autospec=True)
    def test_book_isbn(self, mock_author, mock_book):
        mock_author.name = 'Henry Miller'
        mock_book.title = 'Time of the Assassins'
        mock_book.author = mock_author
        mock_book.retrieve_isbn = MagicMock(return_value='foo123')
        # the next line doesn't work either
        #mock_book.retrieve_isbn.return_value = 'foo123'
        isbn = Book().retrieve_isbn()
        self.assertEqual(isbn, 'foo123')
我的测试失败,出现以下错误:

AssertionError: 'abc123' != 'foo123'
据我所知,当我创建mock_book对象时,对book类实例的任何调用都将被拦截并替换为我分配给mock对象属性的值。“mock_book.retrieve_isbn=MagicMock(return_value='foo123')”这行不是会导致对book类的retrieve_isbn方法的任何调用返回'foo123'吗?或者我没有正确设置测试吗?

这是怎么做的(省去所有无关的东西):


但是在最后一行,您调用了真正的
Book()
,使用
Book().retrieve\u isbn()
。我也可以编写Book=Book(),然后调用Book.retrieve\u isbn(),但这没有什么区别。
@mock.patch('run.models.Book.retrieve_isbn')
def test_book_isbn(self, mock_method):
    mock_method.return_value = 'foo123'
    isbn = Book().retrieve_isbn()
    self.assertEqual(isbn, 'foo123')