Mocking a Django Queryset in order to test a function that takes a queryset

前端 未结 9 1303
青春惊慌失措
青春惊慌失措 2020-12-28 13:55

I have a utility function in my Django project, it takes a queryset, gets some data from it and returns a result. I\'d like to write some tests for this function. Is there a

9条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-28 14:41

    Of course you can mock a QuerySet, you can mock anything.

    You can create an object yourself, and give it the interface you need, and have it return any data you like. At heart, mocking is nothing more than providing a "test double" that acts enough like the real thing for your tests' purposes.

    The low-tech way to get started is to define an object:

    class MockQuerySet(object):
        pass
    

    then create one of these, and hand it to your test. The test will fail, likely on an AttributeError. That will tell you what you need to implement on your MockQuerySet. Repeat until your object is rich enough for your tests.

提交回复
热议问题