<?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" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Oumayma azmi on Medium]]></title>
        <description><![CDATA[Stories by Oumayma azmi on Medium]]></description>
        <link>https://medium.com/@oumaymaazmi?source=rss-128c8dff58bd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*_jP1wlD5bC-xZJIO</url>
            <title>Stories by Oumayma azmi on Medium</title>
            <link>https://medium.com/@oumaymaazmi?source=rss-128c8dff58bd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 17:29:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@oumaymaazmi/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Unlocking the Power of Parameterized Testing in Spring Boot with JUnit5 and Mockito]]></title>
            <link>https://medium.com/@oumaymaazmi/unlocking-the-power-of-parameterized-testing-in-spring-boot-with-junit5-and-mockito-e44dc4a8e7f5?source=rss-128c8dff58bd------2</link>
            <guid isPermaLink="false">https://medium.com/p/e44dc4a8e7f5</guid>
            <category><![CDATA[junit-5]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[it]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[mockito]]></category>
            <dc:creator><![CDATA[Oumayma azmi]]></dc:creator>
            <pubDate>Sat, 09 Nov 2024 23:34:41 GMT</pubDate>
            <atom:updated>2024-11-15T14:27:54.079Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dR2xNH0uBPrVuV4S5x9KFg.jpeg" /></figure><h3>Introduction</h3><p>Parameterized testing is a powerful technique that enables developers to run the same test multiple times with different input parameters, While initially introduced in JUnit 4, parameterized testing has been significantly improved in JUnit 5 with added annotations and increased flexibility, making it easier to create complex test scenarios with minimal setup.</p><p>In this blog post, we’ll explore how to effectively implement parameterized tests in Spring Boot applications using JUnit 5 and Mockito.</p><h4>Why Parameterized Testing ?</h4><p><strong>Reduces Code Duplication: </strong>Instead of writing separate tests for each set of input parameters, you can use a single parameterized test.</p><p><strong>Improves Test Maintainability: </strong>Parameterized tests are more concise and easier to update when requirements change.</p><p><strong>Makes Edge Cases More Visible: </strong>Parameterized tests make it easier to identify and address boundary conditions.</p><p><strong>Increases Test Coverage Efficiently: </strong>A single parameterized test can replace multiple individual tests.</p><h3>Prerequisites</h3><ul><li>Spring Boot 2.x or higher</li><li>JUnit 5</li><li>Mockito</li><li>Basic understanding of unit testing</li></ul><h3>Dependencies</h3><p>To get started with parameterized tests in a Spring Boot application, you’ll need to add the spring-boot-starter-test dependency, which includes JUnit, Mockito, and other useful testing libraries. Here’s how to add it in both Maven and Gradle:</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt;<br>    &lt;scope&gt;test&lt;/scope&gt;<br>&lt;/dependency&gt;</pre><pre><br>testImplementation &#39;org.springframework.boot:spring-boot-starter-test</pre><h3>How to build a parametrize test ?</h3><p>The fundamental building block of a parameterized test is the @ParameterizedTest annotation, which allows you to run the same test multiple times with different input values.</p><p>For example, the following code demonstrates a test that checks if a number is odd:</p><pre>@ParameterizedTest<br>@ValueSource(ints = {1, 2, 3, 4, 5})<br> void testIsOdd(int number) {<br>   assertTrue(number % 2 != 0);<br> }</pre><p>JUnit 5 provides several annotations that can be used to specify the source of parameters :</p><h4>1- @ValueSource :</h4><p>Provides a single array of primitive values (e.g., int, double, String).</p><pre>@ParameterizedTest<br>@ValueSource(strings = {&quot;test&quot;,&quot; hello&quot;,&quot;hello &quot;, &quot;hello test&quot;})<br>void isStringContainsSpace(String name) {<br>     assertTrue(StringUtility.isStringContainsSpace(number));<br>}</pre><p>JUnit will run this test foor times and each time assigns one argument from the array to the method parameter.</p><h4>2- @EnumSource :</h4><p>@EnumSource allows you to run a test with each constant in an enum, which is helpful when you want to ensure your code handles all possible values of an enum properly.</p><pre>@ParameterizedTest<br>@EnumSource(AccessLevel.class)<br>void testHasAdminAccess(AccessLevel level) {<br>    boolean expected = (level == AccessLevel.ADMIN);<br>    assertEquals(expected, accessService.hasAdminAccess(level));<br>}</pre><h4>3- @CsvSource :</h4><p>The @CsvSource annotation allows you to specify parameters as comma-separated values, making it ideal for tests with multiple parameters.</p><p>Each line in @CsvSource provides a separate set of arguments for the test.</p><pre>@ParameterizedTest<br>@CsvSource({<br>        &quot;REGULAR, 100.0, 5.0&quot;,<br>        &quot;MEMBER, 100.0, 10.0&quot;,<br>        &quot;VIP, 100.0, 20.0&quot;<br>}, delimiter = &#39;,&#39;)<br>void testCalculateDiscount(CustomerType type, double amount, double expectedDiscount) {<br>   double result = discountService.calculateDiscount(type, amount);<br>   assertEquals(expectedDiscount, result);<br>}</pre><p>If you have a large dataset and want to keep your tests more manageable, you can use @CsvFileSource to load data from a CSV file instead.</p><h4>4- @MethodSource :</h4><p>The @MethodSource annotation allows you to reference a method that returns a stream or collection of arguments, allowing for more complex data and logic.</p><p>We’ll explore an example with inheritance, which demonstrates flexibility when testing different subclasses or configurations in a single test.</p><p>Imagine we have an abstract class PaymentProcessor with implementations like CreditCardProcessor and PayPalProcessor. We want to test a common method, processPayment, with various amounts and configurations to ensure each subclass behaves as expected.</p><p>Here’s your class setup :</p><pre>public abstract class PaymentProcessor {<br>    public abstract boolean processPayment(double amount);<br>}<br><br>// CreditCardProcessor.java<br>public class CreditCardProcessor extends PaymentProcessor {<br>    @Override<br>    public boolean processPayment(double amount) {<br>        // Example logic: fails if the amount exceeds a limit<br>        return amount &lt;= 1000;<br>    }<br>}<br><br>// PayPalProcessor.java<br>public class PayPalProcessor extends PaymentProcessor {<br>    @Override<br>    public boolean processPayment(double amount) {<br>        // Example logic: PayPal allows up to $2000<br>        return amount &lt;= 2000;<br>    }<br>}</pre><pre>class PaymentProcessorTest {<br><br>    static Stream&lt;Arguments&gt; paymentProcessorProvider() {<br>        return Stream.of(<br>            Arguments.of(new PayementRecord(new CreditCardProcessor(), 500, &quot;test card success&quot;,true)), // Expected to succeed<br>            Arguments.of(new PayementRecord(new CreditCardProcessor(), 1500, &quot;test card failed&quot;,false)), // Exceeds limit<br>            Arguments.of(new PayementRecord(new PayPalProcessor(), 1500, &quot;test paypalcard success&quot;,true)), // Within PayPal limit<br>            Arguments.of(new PayementRecord(new PayPalProcessor(), 2500, &quot;test paypalcard failed&quot;,false)) // Exceeds PayPal limit<br>        );<br>    }<br><br>    @ParameterizedTest(Named=&quot;{0}&quot;) // Uses the test description as the display name<br>    @MethodSource(&quot;paymentProcessorProvider&quot;)<br>    void testProcessPayment(PayementRecord paymentParam) {<br>        PaymentProcessor processor = paymentRecord.paymentProcessor();<br>        boolean result = processor.processPayment(paymentRecord.amount());<br>        assertEquals(paymentParam.expectedResult, result);<br>    }<br><br> private record PayementRecord (<br>            PaymentProcessor paymentProcessor,<br>            Integer  amount,<br>            String testDescription,<br>            boolean  expectedResult<br>    ) {}<br>}</pre><p><em>The</em><strong><em>paymentProcessorProvider</em></strong><em>method creates test data by returning a </em><em>Stream&lt;Arguments&gt;, where each argument is an instance of </em><em>PaymentRecord</em></p><h3>Conclusion</h3><p>Parameterized testing with JUnit 5 and Mockito in Spring Boot applications can significantly improve your test coverage while keeping your test code DRY and maintainable.</p><p>Remember that good tests are an investment in your application’s future, making it easier to maintain and modify your code with confidence.</p><p>Happy testing!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e44dc4a8e7f5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>