How can I mock sqlite3.Cursor

后端 未结 3 1216
你的背包
你的背包 2021-02-14 12:06

I\'ve been pulling my hair out trying to figure out how to mock the sqlite3.Cursor class specifically the fetchall method.

Consider the followi

3条回答
  •  一整个雨季
    2021-02-14 12:42

    You can't mock everything and databases are particularly tricky. I often find that the right thing to do (esp. with Sqlite since it's so easy) is to load up a test database with mock data and use that in the tests (i.e. fixtures). After all, what you really need to test is whether your code is accessing and querying the database correctly.

    The question you are usually trying to answer in a test like this is "If there is X data in the DB and I execute query Y, does that query return Z like I expect", or at a higher level "If I pass parameter X to my method, does it return value Z (based on getting Y from the db)."

    In your example, the real question is "Is SELECT * FROM foo where name = ? the right query in this method?" but you don't answer it if you mock the response.

提交回复
热议问题