Let us assume that the next feature that I have to develop is to store some data on a database. Following the TDD paradigm, I have to first write a failing test. It is not clear to me how I can approach this task, considering that I am using JDBC. The simplest way I can think of is to define a function "storeDataOnDB" and using some framework like Mockito check that the function is called one time. I don't like this solution. Let us continue the TDD approach, next I would write the minimum amount of code that makes the test pass. Simply calling the function would make the test pass, but I am not actually storing anything on the db. Moreover, I am not checking whether I am storing the correct data.
Another solution would be to implement an integration test using a test db and verify that the data are stored correctly. But this is an integration test, while in TDD I am trying to write a unit test.
So, what would be the best method to apply TDD on this feature? Thanks.
CodePudding user response:
in TDD I am trying to write a unit test.
You should drop this constraint -- TDD isn't about "unit" tests, not really (see Chapter 32 of Test Driven Development by Example). It's about "programmer" tests - the small scale tests that act as scaffolding while writing the code.
The tests are there to serve your needs, not the other way around.
There is a trick, though, that you should be aware of: you will often want a design that separates your complicated logic from the parts that actually communicate with the database. Between the two sits a seam (see Working Effectively With Legacy Code, chapter 4), allowing you to write tests with substitute implementations for the part that needs to talk to the database.
The part that actually talks to the database? The ideal is code that is "so simple there are obviously no deficiencies". The expectation here being that if we make the code boring enough, we won't need to change it very often after we get it right (often this sort of code lives unchanged until it is eventually removed completely).
TDD is an awareness of the gap between decision and feedback during programming, and techniques to control that gap.
"Unit test" is not the only permitted technique.