Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would you approach TDD-ing a spring web application [closed]

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?

like image 341
Radi Radichev Avatar asked Sep 04 '13 16:09

Radi Radichev


1 Answers

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:

  • They test one thing (i.e. method calls to other classes / beans are frowned upon)
  • They have a lean setup (i.e. no loading of test data into a database, no transactions, no huge app context)

Integration tests, on the other hand:

  • Are slow (create database connection, loading test data into database, big setup step to wire many beans, configure spring, ...)
  • Brittle (because of the many dependencies)
  • If they fail, you only know that it's somewhere in the 500'000 lines of code that were executed.

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).

like image 65
Aaron Digulla Avatar answered Oct 20 '22 01:10

Aaron Digulla