Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Am I unit testing or integration testing?

I am starting out with automated testing and I would like to test one of my data access methods. I am trying to test what the code does if the database returns no records.

Is this something that should be done in a unit test or an integration test?

Thanks

like image 751
ilivewithian Avatar asked Feb 05 '09 16:02

ilivewithian


2 Answers

My perspective is that you should categorize the test based on scope:

  • A unit test can be run standalone without any external dependencies (File IO, Network IO, Database, External Web Services).
  • An integration test can touch external systems.

If the test requires a real database to run then call it an integration test and keep it separate from the unit tests. This is important because if you mix integration and unit tests than you make your code less maintainable.

A mixed bag of tests mean that new developers may need a whole heap of external dependencies in order to run the test suite. Imagine that you want to make a change to a piece of code that is related to the database but doesn't actually require the database to function, you're going to be frustrated if you need a database just to run the tests associated with the project.

If the external dependency is difficult to mock out (for example, in DotNet, if you are using Rhino Mocks and the external classes don't have interfaces) then create a thin wrapper class that touches the external system. Then mock out that wrapper in the unit tests. You shouldn't need a database to run this simple test so don't require one!

like image 140
Iain Avatar answered Oct 03 '22 08:10

Iain


If your test code connects to an actual database and relies on the presence of certain data (or lack of data) in order for the test to pass, it's an integration test.

I ususally prefer to test something like this by mocking out the component that the "data access method" used to get the actual data, whether that's a JDBC connection or web service proxy or whatever else. With a mock, you say "when this method is called, return this" or "make sure that this method is called N times", and then you tell the class under test to use the mock component rather than the real component. This then is a "unit test", because you are testing how the class under test behaves, in a closed system where you've declared exactly how the other components will behave. You've isolated the class under test completely and can be sure that your test results won't be volatile and dependent on the state of another component.

Not sure what language/technology you are working with, but in the Java world, you can use JMock, EasyMock, etc for this purpose.

like image 25
matt b Avatar answered Oct 03 '22 07:10

matt b