How to write Unit Tests for functions that rely on dynamic data?

后端 未结 6 2148
萌比男神i
萌比男神i 2021-02-06 01:30

Lets say you have a website, that uses a function to retrieve data from the database and returns the result to be displayed/parsed/etc...

Since the data that is retrieve

6条回答
  •  后悔当初
    2021-02-06 02:10

    Unit tests, in their ideal form, should only test one thing. In this case, you're testing two things:

    1. the logic of your function
    2. the database retrieval

    So I would suggest the following refactor:

    1. Move the database retrieval logic into a separate function
    2. Have the function you want to test call that other function
    3. Mock out the function that returns data so you can unit test just the logic of your app
    4. If it makes sense (if you're just relying on another library to do this, then hopefully that lib already has tests), write a unit test for the dynamic retrieval function, where you can't test specifics, but can can test the structure and reasonableness of the data returned (e.g. it has all the fields set, and is a time within 5 seconds of now).

    Also, typically it's a good idea to run unit tests in a test environment where you have complete control over what's stored in the database. You don't want to run these against production data.

提交回复
热议问题