开发者

Junit good practices

开发者 https://www.devze.com 2023-04-12 04:58 出处:网络
I have a code which retrieves few information from Database. For example if you pass person Id, method will return you person details like:

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 retrie开发者_如何学Gove 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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消