简体   繁体   English

为什么这个带有模拟对象的Python / Django单元测试不起作用?

[英]Why Doesn't This Python/Django Unit Test with Mock Objects Work?

I'm having trouble understanding how to write a Python 3 unit test that uses mock objects to mock an instance method for a Django model. 我在理解如何编写使用模拟对象模拟Django模型的实例方法的Python 3单元测试时遇到麻烦。 Here are my models and the test: 这是我的模型和测试:

# 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')

My test fails with this error: 我的测试失败,并显示以下错误:

AssertionError: 'abc123' != 'foo123'

As I understand it, when I create the mock_book object, any calls to instances of the Book class will be intercepted and replaced with the values I assign to the mock object's attributes. 据我了解,当我创建模拟对象对象时,对Book类实例的任何调用都将被拦截,并替换为我分配给模拟对象属性的值。 Isn't the line "mock_book.retrieve_isbn = MagicMock(return_value='foo123')" going to cause any calls to the Book class's retrieve_isbn method to return 'foo123' or have I not set up my test correctly? “ mock_book.retrieve_isbn = MagicMock(return_value ='foo123')”行是否会导致对Book类的retrieve_isbn方法的任何调用返回“ foo123”,还是我没有正确设置测试?

This is how to do it (leaving out all the extraneous stuff): 这是这样做的方法(忽略所有多余的东西):

@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')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM