rot
rot

Reputation: 121

Junit good practices

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.

Upvotes: 1

Views: 710

Answers (2)

Ryan Stewart
Ryan Stewart

Reputation: 128919

It sounds like you're talking about something like a Data Access Object. I'd say it's essential to test that kind of thing with a real database. Look at H2 for a fast, in-memory database that's excellent for testing. Create your populated object, use your persistence code to save it to the database and then to load it back. Then make sure the object you get back has the same state as what you saved in the first place.

Consider using the Spring test framework for help managing transactions in persistence tests and for general test support if you're using Spring elsewhere.

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1503290

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.

Upvotes: 2

Related Questions