Skip to content

Unit Test: Ports and Adapters

Fabian Schmengler edited this page Oct 9, 2017 · 2 revisions

These exercises give an introduction to the ports and adapters architecture for more efficient unit testing.

Exercise 1: Customer session

In the ExerciseContact module, replace the dependency to the session model in Service\CreateInquiry with a custom interface (port), as described in the slides.

Write two implementations (adapters), one for tests and one for Magento.

Exercise 2: Product repository

The ProductBrandRepository interface from Integration-Test:-Database-Layer is another example for a port.

interface ProductBrandRepositoryInterface
{
    /**
     * @param string $brand
     * @return ProductInterface[]
     */
    getProductsByBrand($brand);
}

Check out the solution-integration-test-2 branch of ExerciseBrand, take the BrandList block and extract the business logic to a decoupled class.

The business logic can be described as "list all products for brand of current product, except the current product itself"

a possible interface for the newly created class would be

interface BrandListProvider
{
    /**
     * @param ProductInterface $product
     * @return string
     */
    public function getBrandName(ProductInterface $product);
    /**
     * @param ProductInterface $product
     * @return ProductInterface[]
     */
    public function getOtherProductsOfSameBrand(ProductInterface $product);
}

But you can also pass the current product via constructor instead.

Implement this interface with unit tests and use appropiate test doubles.