My classes are following this structureService Tier (creates and maps InputDTO to DB Data)DAO Tier (actually executes DB calls)When I write service tier JUnit tests, the DAO tier is called, and this expects an actual DB connection and getting data from the DB.Should I be mocking the DAO tier completely from the service tier, or should I be mocking the DB connection and data received from the DB?Secondly, the app expects certain data from a cache.For JUnit run time, there is no cache, so how should this be handled? The service tier method includes looking up the cache to get the details.
What should I mock in tests of an application with service tier and DAO tier?
java;unit testing;mocking;junit
I'm going to talk about Test Doubles, if you haven't run across this term then you'll probably wan to read Martin Fowler's article link first.For the Database testing - If you are following a pure Unit testing approach then you would use a Stub or a Mock type of Test Double to mock out the DB connection and its responses. If you are using a Mock then I would recommend using Mockito, JMock or your other favourite mocking tool.  However, this is quite laborious when it comes to testing a large third party resource such as a database.For the Database testing - If you are following a slightly looser definition of unit testing, then you could use a Fake Test Double. In your particular case, this would be an in memory database such as HSQL.  This is a very popular way of 'unit' testing your database layer. Some will argue that this is not unit testing, and that it is integration testing instead. I think that's actually OK - the fact of the matter is, you have some tests excising your code :-)For the cache testing - A Stub style of Test Double is likely to be your friend here - depending on how complex the cache API is.HTH!