When unit testing, do you have to use a database to test CRUD operations?

后端 未结 7 1010
广开言路
广开言路 2021-02-09 21:11

When unit testing, is it a must to use a database when testing CRUD operations? Can sql lite help with this? Do you have to cre-create the db somehow in memory?

I am usi

7条回答
  •  孤街浪徒
    2021-02-09 21:27

    When unit testing, is it a must to use a database when testing CRUD operations?

    Assuming for a moment that you have extracted interfaces round said CRUD operations and have tested everything that uses said interface via mocks or stubs. You are now left with a chunk of code that is a save method containing a bit of code to bind objects and some SQL.

    If so then I would declare that a "Unit" and say you do need a database, and ideally one that is at least a good representation of your database, lest you be caught out with vender specific SQL.

    I'd also make light use of mocks in order to force error conditions, but I would not test the save method itself with just mocks. So while technically this may be an integration test I'd still do it as part of my unit tests.

    Edit: Missed 2/3s of your question. Sorry.

    Can sql lite help with this?

    I have in the past used in memory databases and have been bitten as either the database I used and the live system did something different or they took quite some time to start up. I would recommend that every developer have a developer local database anyway.

    Do you have to cre-create the db somehow in memory?

    In the database yes. I use DbUnit to splatter data and manually keep the schema up to date with SQL scripts but you could use just SQL scripts. Having a developer local database does add some additional maintenance as you have both the schema and the datasets to keep up to data but personally I find is worth while as you can be sure that database layer is working as expected.

提交回复
热议问题