By my understanding, a "unit test" is a test that makes assertions about the "smallest testable unit" - and an "integration test" is a test that depends on integration with an external system, e.g. database, mail server, REST API, etc.

It occurs to me that a test could fit both of those classifications.

Let's say we have a User repository class, that depends on a database connection object.

Let's say I write a test that calls a findByEmail() method on the repository class - I can't test this independently of a real database connection, because I can't make any assertions about the database behavior and whether the query is actually going to find what I think it is. (For example, I might have composed a query that turns out to be case-sensitive, when the specification says it's supposed to be case-insensitive.)

I could mock the database connection and make assertions about the generated SQL query, but that doesn't prove anything - a mock database connection is merely a spy testing an implementation detail, right? It doesn't prove that the query does what I think it does.

So the "smallest testable unit" in this case is the User repository with a live database connection, which makes it a unit test.

However, it's also an integration test, since it integrates with an external DBMS, correct?

Would you describe this test as a unit test, integration test, or both?

Am I correct to think that the definitions of "unit test" and "integration test" can overlap?

If you agree that these definitions overlap, does one definition trump the other? (That is, if it fits the definition of integration test, maybe it's not a unit test? or vice-versa?)

  • These terms have never had sufficiently rigorous definitions to distinguish them clearly. My personal answer would be to drop "testable" from your unit test definition, and claim that there is no overlap between unit and integration testing, but rather that some units need to be refactored for testability, and on rare occasions, there might even be a unit that's not (usefully) testable.
    – Ixrec
    Nov 14, 2015 at 11:22