<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Abdelsalam Mohamed]]></title><description><![CDATA[Passionate software engineer and avid learner. I write about Java, Spring Boot, and the broader realm of software development. Join me on the journey of continu]]></description><link>https://abdelsalam.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Tue, 01 Sep 2026 12:12:14 GMT</lastBuildDate><atom:link href="https://abdelsalam.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Effective TDD Practices in Spring Boot for Backend Applications]]></title><description><![CDATA[Test-Driven Development (TDD) is a software development approach where tests are written before the code that needs to be tested. This method emphasizes the creation of automated tests to define desired improvements or new functionalities before the ...]]></description><link>https://abdelsalam.hashnode.dev/effective-tdd-practices-in-spring-boot-for-backend-applications</link><guid isPermaLink="true">https://abdelsalam.hashnode.dev/effective-tdd-practices-in-spring-boot-for-backend-applications</guid><category><![CDATA[Java]]></category><category><![CDATA[Testing]]></category><category><![CDATA[backend]]></category><category><![CDATA[TDD (Test-driven development)]]></category><category><![CDATA[Springboot]]></category><category><![CDATA[Spring]]></category><dc:creator><![CDATA[Abdelsalam Mohamed]]></dc:creator><pubDate>Fri, 08 Mar 2024 23:43:37 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1709941345553/941f48e0-a5a7-4297-ad44-bfd714ed8945.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Test-Driven Development (TDD) is a software development approach where tests are written before the code that needs to be tested. This method emphasizes the creation of automated tests to define desired improvements or new functionalities before the actual implementation. In the realm of Spring Boot for backend development, TDD ensures that your application is built with a focus on testable, maintainable, and robust code.</p>
<h2 id="heading-tdd-involves-a-repetitive-cycle-often-described-as-red-green-refactor">TDD involves a repetitive cycle often described as red-green-refactor:</h2>
<ol>
<li><p><strong>Red</strong>: Write a failing test that defines a new function or improvement.</p>
</li>
<li><p><strong>Green</strong>: Write the minimal amount of code necessary to pass the test.</p>
</li>
<li><p><strong>Refactor</strong>: Clean up the code while keeping it functional.</p>
</li>
</ol>
<p>In a Spring Boot backend application, this translates to a continuous cycle of enhancing the business logic, repositories, services, and helper components through tests.</p>
<h2 id="heading-feature-to-implement"><strong>Feature to Implement</strong>:</h2>
<p>Adding a new product with validation to ensure the product name is unique and the initial stock level is not negative.</p>
<h3 id="heading-step-1-write-the-failing-test-red-phase"><strong>Step 1: Write the Failing Test (Red phase)</strong></h3>
<p>Start by writing a test for the service method that adds a new product:</p>
<p>We begin with a test case that expects an exception when attempting to add a product with a duplicate name.</p>
<pre><code class="lang-java"><span class="hljs-meta">@SpringBootTest</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ProductServiceTest</span> </span>{

    <span class="hljs-meta">@MockBean</span>
    <span class="hljs-keyword">private</span> ProductRepository productRepository;

    <span class="hljs-meta">@Autowired</span>
    <span class="hljs-keyword">private</span> ProductService productService;

    <span class="hljs-meta">@Test</span>
    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">shouldThrowExceptionWhenAddingProductWithDuplicateName</span><span class="hljs-params">()</span> </span>{
        String productName = <span class="hljs-string">"UniqueProductName"</span>;
        when(productRepository.existsByName(productName)).thenReturn(<span class="hljs-keyword">true</span>);

        Product newProduct = <span class="hljs-keyword">new</span> Product(productName, <span class="hljs-number">20</span>);

        assertThrows(ProductAlreadyExistsException.class, () -&gt; productService.addProduct(newProduct));
    }
}
</code></pre>
<h3 id="heading-step-2-implement-the-minimal-code-to-pass-the-test-green-phase"><strong>Step 2: Implement the Minimal Code to Pass the Test (Green Phase)</strong></h3>
<p>Adjust the <code>ProductService</code> to include a check for existing product names before adding a new product.</p>
<pre><code class="lang-java"><span class="hljs-meta">@Service</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ProductService</span> </span>{

    <span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> ProductRepository productRepository;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">ProductService</span><span class="hljs-params">(ProductRepository productRepository)</span> </span>{
        <span class="hljs-keyword">this</span>.productRepository = productRepository;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> Product <span class="hljs-title">addProduct</span><span class="hljs-params">(Product product)</span> </span>{
        <span class="hljs-keyword">boolean</span> exists = productRepository.existsByName(product.getName());
        <span class="hljs-keyword">if</span> (exists) {
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> ProductAlreadyExistsException(<span class="hljs-string">"A product with the name "</span> + product.getName() + <span class="hljs-string">" already exists."</span>);
        }
        <span class="hljs-keyword">return</span> productRepository.save(product);
    }
}
</code></pre>
<h3 id="heading-step-3-refactor-the-code-refactor-phase"><strong>Step 3: Refactor the Code (Refactor Phase)</strong></h3>
<p>After ensuring the code passes the test, we refactor it to improve clarity and maintainability, without altering the functionality.</p>
<pre><code class="lang-java"><span class="hljs-function"><span class="hljs-keyword">public</span> Product <span class="hljs-title">addProduct</span><span class="hljs-params">(Product product)</span> </span>{
    assertProductDoesNotExist(product.getName());
    <span class="hljs-keyword">return</span> productRepository.save(product);
}

<span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">void</span> <span class="hljs-title">assertProductDoesNotExist</span><span class="hljs-params">(String productName)</span> </span>{
    <span class="hljs-keyword">if</span> (productRepository.existsByName(productName)) {
        <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> ProductAlreadyExistsException(<span class="hljs-string">"Product with name "</span> + productName + <span class="hljs-string">" already exists."</span>);
    }
}
</code></pre>
<h3 id="heading-benefits-of-tdd-in-spring-boot-backend-applications">Benefits of TDD in Spring Boot Backend Applications</h3>
<ul>
<li><p><strong>Ensures Reliability</strong>: By defining tests first, you can be confident that your code meets the specified requirements and handles edge cases properly.</p>
</li>
<li><p><strong>Facilitates Better Design</strong>: TDD encourages you to think about how to structure your code for testability, which often results in cleaner, more modular code.</p>
</li>
<li><p><strong>Enables Safe Refactoring</strong>: With a comprehensive test suite, you can refactor your code with confidence, knowing that your changes won't introduce regressions.</p>
</li>
</ul>
<p>By adhering to the TDD methodology in Spring Boot, you create a solid foundation for your backend applications, ensuring they are robust, easy to maintain, and well-tested. This approach not only helps in achieving high-quality code but also aligns with agile practices, accommodating changes and new features with ease.</p>
]]></content:encoded></item></channel></rss>