DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • A General Overview of TCPCopy Architecture
  • Cypress vs. Selenium: Choosing the Best Tool for Your Automation Needs
  • Developers Are Scaling Faster Than Ever: Here’s How Security Can Keep Up
  • Keep Your Application Secrets Secret

Trending

  • Go 1.24+ Native FIPS Support for Easier Compliance
  • Software Delivery at Scale: Centralized Jenkins Pipeline for Optimal Efficiency
  • Intro to RAG: Foundations of Retrieval Augmented Generation, Part 2
  • Implementing API Design First in .NET for Efficient Development, Testing, and CI/CD
  1. DZone
  2. Software Design and Architecture
  3. Microservices
  4. Testing Repository Adapters With Hexagonal Architecture

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.

By 
David Cano user avatar
David Cano
·
Mar. 07, 23 · Tutorial
Likes (9)
Comment
Save
Tweet
Share
8.4K Views

Join the DZone community and get the full member experience.

Join For Free

When 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:

  1. Presentation/controller
  2. Service (business logic)
  3. 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:

DTO

On the contrary, with hexagonal architecture, the actual persistence related classes are all defined based on the domain model.

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:

Java
 
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:

Java
 
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:

Java
 
public class StudentRepositoryInMemoryIT extends StudentRepositoryTest {

    @BeforeEach
    public void setup() {
        super.studentRepository = new StudentRepositoryInMemory();
    }

}


Or a bit more elaborated integration test for JPA with Postgres:

Java
 
@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:

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 the student-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 the student-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.

Architecture Repository (version control) Testing

Published at DZone with permission of David Cano. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • A General Overview of TCPCopy Architecture
  • Cypress vs. Selenium: Choosing the Best Tool for Your Automation Needs
  • Developers Are Scaling Faster Than Ever: Here’s How Security Can Keep Up
  • Keep Your Application Secrets Secret

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!