<?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 PrajwalS on Medium]]></title>
        <description><![CDATA[Stories by PrajwalS on Medium]]></description>
        <link>https://medium.com/@prajwals12021999?source=rss-c01632a41482------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*OqJMGze32vX6CZBd</url>
            <title>Stories by PrajwalS on Medium</title>
            <link>https://medium.com/@prajwals12021999?source=rss-c01632a41482------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 21:06:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@prajwals12021999/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[Why Unit Tests Aren’t Enough: Integration Testing with Spring AOP]]></title>
            <link>https://medium.com/@prajwals12021999/why-unit-tests-arent-enough-integration-testing-with-spring-aop-cff2cd06f32a?source=rss-c01632a41482------2</link>
            <guid isPermaLink="false">https://medium.com/p/cff2cd06f32a</guid>
            <category><![CDATA[integration-testing]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[spring-aop]]></category>
            <category><![CDATA[mocking]]></category>
            <dc:creator><![CDATA[PrajwalS]]></dc:creator>
            <pubDate>Tue, 16 Sep 2025 14:41:46 GMT</pubDate>
            <atom:updated>2025-09-16T14:41:46.021Z</atom:updated>
            <content:encoded><![CDATA[<h3>Unit Tests Aren’t Enough: Integration Testing with Spring AOP</h3><p>Unit tests validate logic. Integration tests validate reality. See how this applies to Spring AOP with a sanitize example.</p><p>When it comes to testing in Spring, many teams lean heavily on <strong>unit tests with mocks</strong>. Mocks are fast, easy to set up, and let you test business logic in isolation. But when you introduce <strong>AOP (Aspect-Oriented Programming)</strong> — things like logging, transactions, security, or data sanitization — mocks can quietly betray you.</p><p>Why? Because AOP works by creating <strong>runtime proxies</strong> around your beans. A mock never goes through those proxies, which means it can’t tell you whether your aspect was even applied. Your unit tests may all pass while your production system happily leaks sensitive data or ignores transaction boundaries.</p><p>This is where <strong>integration testing</strong> shines. By running against the real Spring context, integration tests verify not just your business logic but also that your aspects are actually active and doing their job.</p><p>To make this concrete, let’s look at an example: a simple SanitizeAspect.</p><blockquote>This aspect comes from the Spring Certification training material. However, the <strong>unit tests</strong> and <strong>integration tests</strong> shown here are written by me to demonstrate the difference between mocking and real context testing. Full tests can be found on my Github page - <a href="https://github.com/Prajwal-S-6/Spring-Certification-Path/tree/main/module-02/AOP/src/test/java/com/certification/spring/aop/example9">https://github.com/Prajwal-S-6/Spring-Certification-Path/tree/main/module-02/AOP/src/test/java/com/certification/spring/aop/example9</a></blockquote><pre>@Component<br>@Aspect<br>public class SanitizeAspect {<br><br>    @Around(&quot;execution(* com..*(*, *, *))&quot;)<br>    public Object around(ProceedingJoinPoint proceedingJoinPoint) {<br>        MethodSignature methodSignature = (MethodSignature) proceedingJoinPoint.getSignature();<br>        try {<br>            return proceedingJoinPoint.proceed(sanitizeArgumentsIfRequired(proceedingJoinPoint.getArgs(), methodSignature));<br>        } catch (Throwable e) {<br>            throw new RuntimeException(e);<br>        }<br>    }<br><br>    private Object[] sanitizeArgumentsIfRequired(Object[] args, MethodSignature methodSignature) {<br>        Object[] filteredArgs = new Object[args.length];<br>        for (int i = 0; i &lt; args.length; i++) {<br>            filteredArgs[i] = sanitizeArgumentIfRequired(<br>                    args[i],<br>                    methodSignature.getMethod().getParameterAnnotations()[i]<br>            );<br>        }<br>        return filteredArgs;<br>    }<br><br>    private Object sanitizeArgumentIfRequired(Object arg, Annotation[] parameterAnnotations) {<br>        if (containsAnnotationOfType(parameterAnnotations, Sanitize.class) &amp;&amp; arg.getClass() == String.class)<br>            return &quot;***sanitized***&quot;;<br>        else<br>            return arg;<br>    }<br><br>    private boolean containsAnnotationOfType(Annotation[] parameterAnnotations, Class sanitizeClass) {<br>        return Arrays.stream(parameterAnnotations)<br>                .map(Annotation::annotationType)<br>                .anyMatch(sanitizeClass::equals);<br>    }<br>}</pre><p>This aspect ensures that any method parameter annotated with @Sanitize and of type String gets replaced with ***sanitized*** before being passed downstream (e.g., into logs or service calls).</p><h4>1. The Mock-Based Unit Test</h4><p>In the <strong>unit test</strong>, we mock the ProceedingJoinPoint and MethodSignature.</p><pre>@Test<br>public void shouldProceedWithSanitizedArgs() throws Throwable {<br>    ProceedingJoinPoint proceedingJoinPoint = mock(ProceedingJoinPoint.class);<br>    MethodSignature signature = mock(MethodSignature.class);<br>    when(signature.getMethod()).thenReturn(SanitizeAspectUnitTest.class.getDeclaredMethod(&quot;argsAnnotatedWithSanitize&quot;, String.class, String.class, String.class));<br>    when(proceedingJoinPoint.getSignature()).thenReturn(signature);<br>    Object[] objects = {&quot;a&quot;, &quot;b&quot;, &quot;c&quot;};<br>    when(proceedingJoinPoint.getArgs()).thenReturn(objects);<br>    when(proceedingJoinPoint.proceed(any())).thenReturn(&quot;Test&quot;);<br><br>    assertEquals(&quot;Test&quot;, sanitizeAspect.around(proceedingJoinPoint));<br>    Object[] expectedArgsTobeCalledWith = {&quot;a&quot;, &quot;***sanitized***&quot;, &quot;***sanitized***&quot;};<br>    verify(proceedingJoinPoint).proceed(expectedArgsTobeCalledWith);<br>}<br><br>@Test<br>public void shouldProceedWithSameArgsForArgsNotAnnotatedWithSanitize() throws Throwable {<br>    ProceedingJoinPoint proceedingJoinPoint = mock(ProceedingJoinPoint.class);<br>    MethodSignature signature = mock(MethodSignature.class);<br>    when(signature.getMethod()).thenReturn(SanitizeAspectUnitTest.class.getDeclaredMethod(&quot;argsNotAnnotatedWithSanitize&quot;, String.class, String.class, String.class));<br>    when(proceedingJoinPoint.getSignature()).thenReturn(signature);<br>    Object[] objects = {&quot;a&quot;, &quot;b&quot;, &quot;c&quot;};<br>    when(proceedingJoinPoint.getArgs()).thenReturn(objects);<br>    when(proceedingJoinPoint.proceed(any())).thenReturn(&quot;Test&quot;);<br><br>    assertEquals(&quot;Test&quot;, sanitizeAspect.around(proceedingJoinPoint));<br>    Object[] expectedArgsTobeCalledWith = {&quot;a&quot;, &quot;b&quot;, &quot;c&quot;};<br>    verify(proceedingJoinPoint).proceed(expectedArgsTobeCalledWith);<br>}</pre><p>This test <em>proves</em> that the aspect <strong>logic itself</strong> works. But it relies on mocks for ProceedingJoinPoint and never goes through the <strong>actual Spring AOP proxy</strong>. If the pointcut expression in @Around was wrong, or if the aspect wasn’t registered as a Spring bean, the test would still pass.</p><p>Lets misconfigure the pointcut expression by changing number of required arguments to 2 and see the result-</p><pre>@Around(&quot;execution(* com..*(*, *))&quot;)<br>    public Object around(ProceedingJoinPoint proceedingJoinPoint) {<br>        MethodSignature methodSignature = (MethodSignature) proceedingJoinPoint.getSignature();<br>        try {<br>            return proceedingJoinPoint.proceed(sanitizeArgumentsIfRequired(proceedingJoinPoint.getArgs(), methodSignature));<br>        } catch (Throwable e) {<br>            throw new RuntimeException(e);<br>        }<br>    }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ye4uLSYon1v1KKKDVTWEQA.jpeg" /></figure><p>The test still passes, as it verifies the aspect’s algorithm, but <strong>not whether it actually runs in your application</strong>.</p><h4>2. The Integration Test</h4><p>In the <strong>integration test</strong>, we wire up Spring with a real bean (TransactionHistoryServiceClient) and call its method:</p><pre>@ExtendWith({SpringExtension.class})<br>@ContextConfiguration(classes = ApplicationConfig.class)<br>class SanitizeAspectIntegrationTest {<br><br>    @Autowired<br>    private TransactionHistoryServiceClient transactionHistoryServiceClient;<br><br><br>    @Test<br>    void shouldSanitizeTheArgs() {<br>        Logger logger = (Logger) LoggerFactory.getLogger(TransactionHistoryServiceClient.class);<br>        ListAppender&lt;ILoggingEvent&gt; listAppender = new ListAppender&lt;&gt;();<br>        listAppender.start();<br>        logger.addAppender(listAppender);<br><br>        transactionHistoryServiceClient.saveTransactionData(&quot;123&quot;, &quot;abc&quot;, &quot;password&quot;);<br><br>        List&lt;ILoggingEvent&gt; logs = listAppender.list;<br><br>        assertEquals(1, logs.size());<br>        assertThat(logs.get(0).getLevel().toString()).isEqualTo(Level.INFO.toString());<br>        assertThat(logs.get(0).getFormattedMessage())<br>                .isEqualTo(&quot;Sending data, identifier = [123], data = [***sanitized***], privateKey = [***sanitized***]&quot;);<br>    }<br>}</pre><p>This test:</p><ul><li>Runs the method through Spring’s <strong>proxy layer</strong>.</li><li>Ensures the aspect is applied in the actual runtime.</li><li>Verifies end-to-end behavior.</li></ul><p>Now, lets run the SanitizeAspectIntegrationTest after misconfiguring the pointcut expression and observe the result -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fmhTf6x-kVibtnEghuR9lw.jpeg" /></figure><p>If the @Around pointcut were misconfigured, or if the SanitizeAspect wasn’t picked up by Spring scanning, <strong>this test would fail</strong>.</p><h3>The Lesson</h3><ul><li><strong>Unit tests with mocks</strong>: confirm the aspect’s <em>logic</em>.</li><li><strong>Integration tests</strong>: confirm the aspect is <em>actually applied</em>.</li></ul><p>If you only wrote the unit tests above, you’d never know if your real TransactionHistoryServiceClient logs were leaking sensitive data. The integration test makes sure your <strong>cross-cutting concern really works in production conditions</strong>.</p><p>That’s why when testing AOP (and other runtime features like transactions, caching, or security), <strong>integration tests are essential</strong> — mocks alone are misleading.</p><blockquote>Thank you for reading this article. Don’t forget to follow me on Medium.</blockquote><blockquote>Inspired by the insights from <a href="https://www.amazon.in/Product-Mindset-Building-Software-Matters/dp/B0FM8PD61G">Product-Mindset-Building-Software-Matters</a>, which emphasizes delivering reliable and valuable software through thoughtful design and testing.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cff2cd06f32a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding @Transactional in Spring: Best Practices and Pitfalls in Tests]]></title>
            <link>https://medium.com/@prajwals12021999/understanding-transactional-in-spring-best-practices-and-pitfalls-in-tests-9813e382082e?source=rss-c01632a41482------2</link>
            <guid isPermaLink="false">https://medium.com/p/9813e382082e</guid>
            <category><![CDATA[tdd]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[integration-testing]]></category>
            <category><![CDATA[transactional]]></category>
            <category><![CDATA[spring]]></category>
            <dc:creator><![CDATA[PrajwalS]]></dc:creator>
            <pubDate>Mon, 15 Sep 2025 13:14:58 GMT</pubDate>
            <atom:updated>2025-09-15T13:14:58.134Z</atom:updated>
            <content:encoded><![CDATA[<p>The @Transactional annotation in Spring is one of the most powerful features to manage database transactions declaratively. However, misuse or misunderstanding can lead to unexpected behaviors, especially in testing and approval workflows.</p><h3>What @Transactional Does</h3><p>When you annotate a method or class with @Transactional, Spring ensures that:</p><ul><li>Spring creates a <strong>proxy</strong> around the object.</li><li>Any method call that enters the proxy is executed <strong>within a transaction</strong>.</li><li>If an exception occurs (unchecked exceptions by default), Spring <strong>rolls back</strong> the transaction.</li></ul><h3>Common Pitfall: @Transactional on Test Classes</h3><p>A common mistake is adding @Transactional on a <strong>JUnit or Spring Boot test class</strong> while also having @Transactional on the service class:</p><p>Example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qnReajTf-DkYi6YJ5sWPCw.png" /></figure><blockquote>Here there are two methods <strong>saveEmployeeWithoutTransaction()</strong> and <strong>saveEmployeeWithTransaction()</strong> (unchecked) exception is thrown when employee id is negative</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*zqlIIBPcmIkD74iazGa_bg.png" /></figure><p>When saveEmployeesWithoutTransaction() is called from the test method it should persist employee with id:10,11,12 as it is running inside Test class transaction only, any exception while saving employee doesn’t trigger a rollback</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2A72ftp4z79SjAdJZ0KHBw.png" /></figure><p>This testcase works as expected. But the problem occurs when the service method is also annotated with @Transactional</p><p><strong>Problem:</strong></p><ul><li>When the test class is transactional, <strong>all service calls inside it participate in the same test transaction</strong>.</li><li>This can lead to misleading behavior during integration testing, as changes might persist unexpectedly or rollbacks behave differently than in production.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7mnmLP8xt-c9UQH1b4nLzQ.png" /></figure><p>Expected zero employees to be saved considering <strong>saveEmployeesWithTransaction()</strong> will rollback all previous operations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*oJO8CvE-QRdINNujJ04Z2A.png" /></figure><p>If a service method throws an exception, it <strong>won’t trigger rollback in the service’s own transaction</strong> because it’s already part of the test transaction.</p><h3>Proposed Solution</h3><h4>Best Practices</h4><ol><li><strong>Don’t put </strong><strong>@Transactional on the test class</strong> if your service methods are transactional. Use it only when you intend for the entire test to roll back automatically. Always prefer to clean the data manually, instead of relying on transactions, and prefer to do so before the tests execute.</li></ol><p><strong>2. Use transaction propagation carefully</strong></p><ul><li>REQUIRES_NEW starts a new, independent transaction.</li><li>NESTED runs inside an existing transaction if one exists.</li></ul><h4>Summary</h4><ul><li>@Transactional ensures atomicity: all operations succeed or none.</li><li>Be cautious with transactional tests — service methods may not behave as expected inside a test transaction.</li><li>Use transaction propagation wisely to control boundaries and rollback behavior.</li></ul><blockquote>Thank you for reading this article. Don’t forget to follow me on Medium.</blockquote><blockquote>Inspired by the insights from <a href="https://www.amazon.in/Product-Mindset-Building-Software-Matters/dp/B0FM8PD61G">Product-Mindset-Building-Software-Matters</a>, which emphasizes delivering reliable and valuable software through thoughtful design and testing.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9813e382082e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>