Getting Started With Unit Testing With Spring Repository
Go Back to Course Outline Repositories https://github.com/terawarehouse/terawarehouse-catalog https://github.com/terawarehouse/tera...
https://www.czetsuyatech.com/2019/06/spring-repository-unit-testing.html
Repositories
- https://github.com/terawarehouse/terawarehouse-catalog
- https://github.com/terawarehouse/terawarehouse-react
Before we start creating our tests, I would like to check the following points:
- LoadDatabase class should not load or save the categories by commenting on the initDatabase method.
- Set the application properties to use PostgreSQL.
- [open application.properties]
[Open pom.xml] Notice that we created a new development-test profile that contains the h2 dependency. Whereas, the default profile development contains all the PostgreSQL specific dependencies as well as Liquibase.
Creating our very first test. As a default, we will have the contextLoads test.
[open TerawarehouseCatalogApplicationTests class]
What’s with the annotations?
- @RunWith(SpringRunner.class) is a bridge between JUnit and Spring. It enables us to use Spring features inside JUnit tests. SpringRunner provides support for loading the ApplicationContext and enables auto-wiring.
- @SpringBootTest autoconfigures the application context by loading the default configuration from the class annotated with @SpringBootApplication when it is not annotated with configuration modifiers like @EnableJpaRepositories, @EntityScan, @ComponentScan, @ContextConfiguration, etc.
- [open H2JpaConfig class] have a look at this class, how it overrides the configuration.
- @TestPropertySource instead of using the application.properties file in the main folder, we will be overriding it with an H2 specific configuration.
Finally, it’s now time to present our very first repository unit test for the category.
[open CategoryRepositoryIntegrationTest]
- Again we have the @RunWith(SpringRunner.class), expect this in all your test classes.
- @DataJpaTest normally use for a JPA specific test. It autoconfigures our data source and entity manager base on the property source which we specified before.
- @DirtiesContext it’s possible for us to modify the state of our database and it’s possible that we will need to set up its initial content every test. Then it's better to supply a new context before the method. Otherwise, since we are in read-only mode just remove this annotation.
[show screenshot of the maven build configuration]
Next, we will start creating our REST API. See you in our next video.
Ja ne.
Post a Comment