Want to improve as a dev?

I send a short email every workday about Spring topics, API development and improving as a dev.

I understand and agree to the privacy policy

Let's Build an API Together - Part 14

08.01.2018 by Jens in API Series | APIs | Newsletter

The black box testing with a RAML tool failed last time, so we are left with unit and our own integration tests. Which brings me to the point what should we use? Should our tests focus more on pure unit testing or more integration tests, testing different parts at the same time?

It depends.

When testing pure business logic, unit testing is a great start. Unit testing a Spring controller, however, comes closer to a gray area. If the controller has complex transformation rule, it should have its own unit tests. However, if it merely returns the domain model, a unit tests doesn’t make sense to me; it would basically test if Spring is doing its work.

When we test our data access object, persistence service or whatever you call it, it also doesn’t make sense to unit test. I’d go with an integration test including the DB access - with an in-memory DB. Mocking the DB, in this case, is too far away from the production circumstances. Also, mocking brings its own drawbacks to the table. One needs to implement a correct mock, so the tests have any value at all. I’ve seen passing bad code because of bad mocks to productions. Sometimes it is also more work to setup good mocks and devs tend to shy away from that and rather don’t test at all, which I think is worse.

Integration test can take more time, depending on the complexity of the used service (DB, Queue, etc.), but they bring the benefit, that our code is tested in combination with other code. It’s quite common that two services pass all their unit tests but fail in combination with certain scenarios. Can be fun to debug if it is not your code ;-)

Anyways, with Spring projects, I made the best experiences so far with unit testing Spring MVC controllers and mocking my own services. Service without external dependencies get unit tested too (with mocks). When the external dependency is a Spring Data Repository, I work with integration tests. If there is a workflow from front to back with business logic, I add integration tests for that.

When you write your tests is up to you and your particular context.

When working in an existing code base, I think TDD is the better approach. However, when prototyping and sketching out ideas, I’d write a working first draft, refactor and rethink it and then start putting in tests; hey sometimes I design while I code…

comments powered by Disqus