The unit tests

The lower level tests we can write are called unit tests. They should test a small portion of code, hence the notion of unit. How you define a unit is up to you; it can be a class or a bunch of closely related classes. Defining this notion will determine what will be mocked (replaced with a dummy object). Are you going to replace the database with a lightweight alternative? Are you going to replace interactions with external services? Are you going to mock-up closely related objects whose behavior is not relevant to the context of what's being tested?

My advice here is to keep a balanced approach. Keep your tests clean and fast, and everything else will follow.

I rarely completely mock the data layer. I tend to use embedded databases for testing. They provide an easy way to load data while testing.

As a rule, I always mock collaboration with external services for two reasons, as follows:

  • The speed of the tests and the possibility to run the tests without connecting to the network
  • To be able to test error cases while communicating with those services

Additionally, there is a subtle difference between mocking and stubbing. We will try to use both approaches to see how they relate to each other.

The right tools for the job

The first barrier for test novices is the lack of knowledge of the good tools and libraries for writing relevant and maintainable tests.

I'm going to list a few here. This list is by no means exhaustive, but it contains the tools we are going to use and that are easily compatible with Spring:

JUnit

The most universally adopted Java test runner. Launched by default by all build tools.

AssertJ

A fluent assertion library. It's way easier to use than Hamcrest.

Mockito

An easy mocking framework.

DbUnit

For mocking and asserting your database content with XML datasets.

Spock

An elegant Groovy DSL to write tests with Behaviour Driven Development (BDD) style (Given/When/Then).

Groovy has a place of choice in my testing toolset. Even if you're not ready yet to put some Groovy code into production, you can easily use the convenience of the language in your tests. With Gradle, this is very easy to do, but we will see that in a few minutes.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.186.79