I have a code which retrieves few information from Database.
For example if you pass person Id, method will return you person details like:
Name: XXX X XXX
Address: XXXXXXXXXXXXX XXXXX
Phone: XXXXXX
In Junit what is the good practice to test this type of code? Is it good practice that Junit to have DB connection?
Is it a good practice, that JUnit will connect to DB and retrieve information for same person Id and do assertion.
Thanks.
For testing the code that really needs to work with the database, you should look at dbunit. As little of the code as possible should know about the database though – allowing you to fake out the “fetch or update the data” parts when testing other components.
I’d strongly advise a mixture of DB tests – lots of unit tests which hit an in-memory database (e.g. HSQLDB) and “enough” integration tests which talk to the real kind of database that will be used in production. You may well want to make sure that all your tests can actually run against both environments – typically develop against HSQLDB, but then run against your production-like database (which is typically slower to set up/tear down) before check-in and in your continuous build.