Search code examples
unit-testingmockingintegration-testing

Is it wrong to favour integration testing over unit testing?


We're running a project on which we started adopting test-driven design long after the development was started.

We have both unit tests and integration tests. Integration tests are run on a real database, initialized in a known state before the tests are run.

As we write tests, we start noticing than even for classes that could be tested in the "standard way", in isolation & with mock objects, it has actually become faster, and cleaner (read: shorter & easier to understand code) to just use real objects/services directly talking to the database, rather than cluttering the test class with complicated mock objects setup.

Is there anything wrong with this approach?


Solution

  • If you are using real objects/services, then you don't know why your tests failed. E.g. you changed something in service implementation, or renamed database field, or there your network is down - you have 50 failed "unit" tests. Also you can't do test-driven development in this case, because dependencies which will be required by class you are testing should be implemented before you writing test. Can you foresee which API will be required by consumers of your service? That will lead to less usable API and code which not used at all (parameters, methods, etc).

    If your tests take a lot of efforts to arrange mocks, then:

    • tests should be short and simple
    • don't verify what other tests already verified
    • dependencies should be easy to interact with
    • try to follow Single Responsibility Principle for your classes (both dependencies and sut)
    • try to follow Tell Don't Ask Principle - instead of asking many questions to dependency, tell it what you want