模拟Django Queryset以测试一个需要查询的功能 [英] Mocking a Django Queryset in order to test a function that takes a queryset

查看:139
本文介绍了模拟Django Queryset以测试一个需要查询的功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Django项目中有一个实用功能,它需要一个查询,从中获取一些数据并返回一个结果。我想为这个功能写一些测试。有没有模拟一个QuerySet?我想创建一个不接触数据库的对象,我可以为它提供要使用的值列表(即一些假的行),然后它将像一个查询器一样运行,并且允许某人对它进行字段查找/ filter / get / all等。



有没有这样的事情已经存在?

解决方案

不是我知道的,但为什么不使用实际的查询?测试框架全部设置为允许您在测试中创建示例数据,并在每次测试中重新创建数据库,因此似乎没有任何理由不使用真实的东西。


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 anyway to 'mock' a QuerySet? I'd like to create an object that doesn't touch the database, and i can provide it with a list of values to use (i.e. some fake rows) and then it'll act just like a queryset, and will allow someone to do field lookups on it/filter/get/all etc.

Does anything like this exist already?

解决方案

Not that I know of, but why not use an actual queryset? The test framework is all set up to allow you to create sample data within your test, and the database is re-created on every test, so there doesn't seem to be any reason not to use the real thing.

这篇关于模拟Django Queryset以测试一个需要查询的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆