Jake Lacey
Jake Lacey

Reputation: 633

Unit Testing a method which queries the database

So I've created a function which accepts an ID, internally queries a database via a repository from the data returned mutations are made to the data depending on different scenarios and then we return the data.

How would I unit test this function? Would I stub the find method on my repository layer to return data so I'm not dependant on connecting on the database?

Upvotes: 1

Views: 418

Answers (1)

zim
zim

Reputation: 2386

i will argue that you can only unit test code which is unit testable. my definition of unit testable code is code that exhibits these properties:

  1. it gets everything it needs from its inputs
  2. all its work is expressed through return values (or throwing exceptions)
  3. it does not produce any side effects

the code you describe violates #1, by going to the database.

to answer your question directly, you would mock the database call and that mock would provide to your function expected data, such that you can mutate it and compare it to an expected output.

but i think the real right answer is to refactor your code, applying the Single Responsibility Principle. your code under test is doing two things (going to the database and mutating the result), instead of doing just one thing.

i would break out the database portion and assign that as Someone Else's Job. then your code under test could take that database result as an input, and its sole job would be to mutate that data and return the result.

that would, imho, make it unit testable. and when you unit test it, you wouldn't have to mock the db at all, as you could simply write the data you wanted to mutate and supply it the function.

Upvotes: 2

Related Questions