I'm looking for advice on how would someone approach creating a spring web application (with hibernate) in a pure TDD fashion. Meaning that you shouldn't write production code without having a failing unit test for it first.
Would you be unit testing the creation of your application context? If yes how would you go about doing that?
Would it be easier to TDD a spring app when using java configuration instead of xml or annotation based configuration?
When you write a test that needs a Spring ApplicationContext
and a database, then this is an integration test, not a unit test. The general rules for unit tests are:
Integration tests, on the other hand:
So for TDD, you try to build beans which you can create without Spring. Write them in such a way that you don't have to start Hibernate or a database. The main reason here is that TDD needs to run the unit tests hundreds of times each day. If they run longer than 10 seconds, you will eventually feel like you're wasting your time waiting for the tests to finish.
The next question is usually how you can test anything useful this way. Well, think of it this way: Hibernate works. It already has many unit tests. Testing hibernate is a waste of time. So you should create an layer in your application which completely hides Hibernate from the code.
Instead of wiring a FooDao
, wire an IFooDao
that has a byId()
method and returns a POJO. In unit tests, you can create a mock implementation that returns a single instance.
When you want to know whether the real FooDao
works, write integration tests for that which call byId()
a few times.
But avoid the "get object from DAO, process object, save object with DAO again". These are three distinct tests (two IT, one UT).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With