John Doherty
John Doherty

Reputation: 4095

Why bother mocking a repository?

This is probably a really lame question but one I need to ask. Why bother mocking a repository ?

If you're creating objects with hard coded values and then using Moq to return them as values from method calls on an interface (i.e. without implementation) what exactly are you testing ?

Upvotes: 4

Views: 158

Answers (3)

dimo414
dimo414

Reputation: 48824

Like the other answers have said, you do this in order to test the client, not the repository (or database, or external service, or whatever), but there's two key reasons why we do this:

  1. To ensure repeatability and create exceptional cases: You want to be able to know that what you're testing doesn't regress over time. If your repository is changing, you can't be certain that what works now also worked previously. Furthermore, you can identify exceptional cases that may not appear in the repository right now (perhaps a user without a Social Security number, or something similarly obscure but possible) and include them in your test, thereby ensuring future compatibility.

  2. To remove dependencies: You want to make testing as simple and as fast as possible. Every external resource a test relies on is one more barrier to regular testing. If you mock your repository, then tests can be run against your client even if the repository doesn't exist, or is missing.

    For example, if a program hooks into a "real" database, their testing suite might use a local (or even in memory) SQLite database to test their DB behavior, and that way the person running the tests doesn't need to configure or connect to an actual database, and any changes or errors that occur don't impact a shared database resource.

Upvotes: 3

sloth
sloth

Reputation: 101072

In this case, or generally when mocking, you do not test your repository, but rather test that a given class, your SUT (System Under Test), uses the repository correctly, e.g. by calling methods (probably in the right order).

Mocks use behavior verification, and not state verification.

That means you use mocks to test if your SUT is behaving correctly, not that is has the correct state at the end of the test case.

Jeremy Miller has some nice blog posts about this topic.

Upvotes: 1

NG.
NG.

Reputation: 22904

You would be testing the clients that use that repository.

I.E. are the services using the repository doing the right thing with your known set of objects.

Upvotes: 1

Related Questions