Testing
Is it that hard?
Several people think that frameworks like Spring go against testing because it's really easy to use the framework and not to know the internals. We think this is half true. In this Spring Data example, we decide it has no sense to write unit tests because you even don't know the repository implementation, you just inject the object and Spring do all the magic for you.
So, we are forgetting about unit testing for a while and focus on the integration tests.
What is giving Jumahuaca for this example? NOTHING. Or almost nothing.
Wait, wait, don't run to StackOverflow we are only saying that this project example is not using the Core Framework but it's really valuable for the test examples. We will show you that testing (integration testing) in Spring Framework is really easy and you should use the same tools Spring is giving to you. Let's see. The test class is SpringDataRepositoryIntegrationTests.java
So prepare yourself for that hard work...
@ExtendWith(SpringExtension.class)
@DataJpaTest
@Import({SpringUvaApiApplication.class,Configuration.class})
That's it. True to be told you have to add H2 dependency in the pom file (check out the pom here) but nothing else.
When you create the fixture you can add data programmatically, as we do in this example:
@Autowired
private TestEntityManager entityManager;
@Autowired
private UvaExchangeRepository repository;
@BeforeEach
public void setup() throws Exception {
UVAExchange exchange1 = new UVAExchange(LocalDate.of(TEST_YEAR_1, TEST_MONTH_1, TEST_DAY_1), TEST_RATE_1);
UVAExchange exchange2 = new UVAExchange(LocalDate.of(TEST_YEAR_2, TEST_MONTH_2, TEST_DAY_2), TEST_RATE_2);
entityManager.persist(exchange1);
entityManager.persist(exchange2);
entityManager.flush();
}
The tests are similar are the integration ones in JDBC-Example, we use Junit5 and AssertJ.
We add a little syntactic sugar with a custom annotation called: @IntegrationTest. It combines @Test annotation with @Tag("integration") one, using a cool feature in junit5 that allows combine annotations. For more detail of this feature please visit this page
The real value in this example is the running example itself. Spring Boot is great because all that amazing out of the box features but it is really easy to start having issues if you did not do things the way Spring was expecting. Very special warning to this line
@Import({SpringUvaApiApplication.class,Configuration.class})
Because this way to separate the configuration will you avoid getting into a lot of brain pains.
So you have no excuses, if you are using Spring Data you can have your integration tests in almost no time.
Last updated
Was this helpful?