Testing Repository Adapters With Hexagonal Architecture
In this article, readers will use a tutorial to learn about testing repository adapters with a hexagonal architecture, including guide code and images.
Join the DZone community and get the full member experience.
Join For FreeWhen applying hexagonal architecture (ports and adapters) with access to infrastructure elements like databases is done by the mean of adapters, which are just implementations of interfaces (ports) defined by the domain. In this article, we are going to provide two implementations of the same repository port, one in-memory and another based on JPA, focusing on how to test both implementations with the same set of tests.
Context
Many software solutions usually developed in the enterprise context have some state that needs to be persisted in a durable store for later access. Depending on the specific functional and non-functional requirements, selecting the correct persistence solution can be hard to make and most likely require an Architecture Decision Record (ADR) where the rationale of the selection, including alternatives and tradeoffs, is detailed. For persisting your application state, most likely, you will look at the CAP Theorem to make the most adequate decision.
This decision process should not delay the design and development of your application’s domain model. Engineering teams should focus on delivering (business) value, not on maintaining a bunch of DDL scripts and evolving a highly changing database schema, for some weeks (or months) later, realize it would have been better to use a document database instead of a relational database.
Also, focusing on delivery domain value prevents the team from taking a domain-related decision based on the constraints of a too-early-taken technical and/or infrastructure-related decision (i.e., the database technology in this case). As Uncle Bob said in this tweet, the architecture shall allow deferring the framework decisions (and infrastructure ones).
Deferring Infrastructure-Related Decisions
Coming back to the database technology example, a way of deferring the infrastructure decision regarding which database technology shall be used, would be starting with a simple in-memory implementation of your repository where the domain entities can be stored in a list in memory. This approach accelerates the discovery, design, and implementation of features and domain use cases, enabling fast feedback cycles with your stakeholders about what matters: Domain Value.
Now, you might be thinking, “but then, I’m not delivering an e2e working feature,” or “how do I verify the feature with an in-memory adapter of my repository?” Here, architecture patterns like Hexagonal Architecture (also known as ports and adapters) and methodologies like DDD (not mandatory for having a clean architecture and ultimately clean code) come into action.
Hexagonal Architecture
Many applications are designed following the classical three-layered architecture:
- Presentation/controller
- Service (business logic)
- Persistence layers
This architecture tends to mix domain definition (e.g., domain entities and value objects) with tables (e.g., ORM entities), usually represented as simple Data Transfer Objects. This is shown below:
On the contrary, with hexagonal architecture, the actual persistence related classes are all defined based on the domain model.
By using the port (interface) of the repository (which is defined as part of the domain model), it is possible to define integration test definitions agnostic of the underlying technology, which verifies the domain expectations towards the repository. Let’s see what this looks like in code in a simple domain model for managing students.
Show Me the Code
So how does this repository port look as part of the domain? It essentially defines the expectations of the domain towards the repository, having all the methods defined in terms of domain ubiquitous language:
public interface StudentRepository {
Student save(Student student);
Optional<Student> retrieveStudentWithEmail(ContactInfo contactInfo);
Publisher<Student> saveReactive(Student student);
}
Based on the repository port specification, it is possible to create the integration test definition, which is only dependent on the port, and agnostic of any underlying technology decision made for persisting the domain state. This test class will have a property as an instance of the repository interface (port) over which the expectations are verified. The next image shows what these tests look like:
public class StudentRepositoryTest {
StudentRepository studentRepository;
@Test
public void shouldCreateStudent() {
Student expected = randomNewStudent();
Student actual = studentRepository.save(expected);
assertAll("Create Student",
() -> assertEquals(0L, actual.getVersion()),
() -> assertEquals(expected.getStudentName(), actual.getStudentName()),
() -> assertNotNull(actual.getStudentId())
);
}
@Test
public void shouldUpdateExistingStudent() {
Student expected = randomExistingStudent();
Student actual = studentRepository.save(expected);
assertAll("Update Student",
() -> assertEquals(expected.getVersion()+1, actual.getVersion()),
() -> assertEquals(expected.getStudentName(), actual.getStudentName()),
() -> assertEquals(expected.getStudentId(), actual.getStudentId())
);
}
}
Once the repository test definition is completed, we can create a test runtime (integration test) for the in-memory repository:
public class StudentRepositoryInMemoryIT extends StudentRepositoryTest {
@BeforeEach
public void setup() {
super.studentRepository = new StudentRepositoryInMemory();
}
}
Or a bit more elaborated integration test for JPA with Postgres:
@Testcontainers
@ContextConfiguration(classes = {PersistenceConfig.class})
@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
public class StudentRepositoryJpaIT extends StudentRepositoryTest{
@Autowired
public StudentRepository studentRepository;
@Container
public static PostgreSQLContainer container = new PostgreSQLContainer("postgres:latest")
.withDatabaseName("students_db")
.withUsername("sa")
.withPassword("sa");
@DynamicPropertySource
public static void overrideProperties(DynamicPropertyRegistry registry){
registry.add("spring.datasource.url", container::getJdbcUrl);
registry.add("spring.datasource.username", container::getUsername);
registry.add("spring.datasource.password", container::getPassword);
registry.add("spring.datasource.driver-class-name", container::getDriverClassName);
}
@BeforeEach
public void setup() {
super.studentRepository = studentRepository;
}
}
Both test runtimes are extending the same test definition, so we can be sure that, when switching from the in-memory adapter to the final JPA-full-featured persistence, no test shall be affected because it’s only needed to configure the corresponding test runtime.
This approach will allow us to define the tests of the repository port without any dependency on frameworks and reuse those tests once the domain is better defined, being more stable, and the team decides to move forward with the database technology that better fulfills the solution quality attributes.
The overall structure of the project is shown in the next image:
Where:
student-domain
: Module with the domain definition, including entities, value objects, domain events, ports, etc. This module has no dependencies with frameworks, being as pure Java as possible.student-application
: Currently, this module has no code since it was out-of-scope of the article. Following hexagonal architecture, this module orchestrates invocations to the domain model, being the entry point of the domain use cases. Future articles will enter more details.student-repository-test
: This module contains the repository test definitions, with no dependencies on frameworks, and only verifies the expectation of the provided repository port.student-repository-inmemory
: In-memory implementation of the repository port defined by the domain. It also contains the integration test, which provides the in-memory adapter of the port to the test definition of thestudent-repository-test
.student-repository-jpa
: JPA implementation of the repository port defined by the domain. It also contains the integration test, which provides the in-memory adapter of the port to the test definition of thestudent-repository-test
. This integration test setup is a bit more complex since it spin-up a basic Spring context together with a Postgres container.student-shared-kernel
: This module is out-of-scope of the article; it provides some utility classes and interfaces for designing the rest of the project.
Conclusion
Using this architectural style for your projects promotes good separation between the domain model and infrastructure elements around it, ensuring the latter will not influence the former while promoting good code quality (clean code) and high maintainability.
The code of this article can be found in my personal GitHub repository.
Published at DZone with permission of David Cano. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments