<?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 Abdirahman Bashir Abdi on Medium]]></title>
        <description><![CDATA[Stories by Abdirahman Bashir Abdi on Medium]]></description>
        <link>https://medium.com/@abdirahman.bashir88?source=rss-f47dde3fea3e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*hmrcs0Uhf4gXcBwGg7dPzg.jpeg</url>
            <title>Stories by Abdirahman Bashir Abdi on Medium</title>
            <link>https://medium.com/@abdirahman.bashir88?source=rss-f47dde3fea3e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 05:50:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@abdirahman.bashir88/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[Integration Testing with Testcontainers and Spring Boot]]></title>
            <link>https://medium.com/@abdirahman.bashir88/integration-testing-with-testcontainers-and-spring-boot-ec0d7217f5cc?source=rss-f47dde3fea3e------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec0d7217f5cc</guid>
            <dc:creator><![CDATA[Abdirahman Bashir Abdi]]></dc:creator>
            <pubDate>Sun, 10 Mar 2024 12:44:33 GMT</pubDate>
            <atom:updated>2024-03-10T13:58:47.705Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*5Asc_OqzWFaY71b0QirRyg.jpeg" /></figure><ol><li><strong>Introduction</strong></li></ol><p><strong><em>Integration testing</em></strong> is a crucial aspect of software development that ensures the seamless interaction and compatibility of various components within a system. It involves evaluating the behavior of the integrated components to validate the system’s end-to-end functionality.</p><p><strong>2. Understanding Testcontainers</strong></p><p>Testcontainers is a versatile Java library designed to streamline integration testing by providing lightweight, disposable instances of common dependencies, such as databases and web browsers, encapsulated within Docker containers. It enables developers to execute integration tests against real instances of these services without relying on external dependencies or manual setup processes.</p><p><strong>Advantages of Integration Testing with Testcontainers</strong></p><ul><li><strong>Consistent Testing Environment:</strong> Testcontainers offers a consistent and isolated testing environment by orchestrating disposable instances of dependencies within Docker containers.</li><li><strong>Elimination of External Dependencies:</strong> Developers can forego the cumbersome task of setting up and managing external services or databases, as Testcontainers automates this process seamlessly.</li><li><strong>Portability:</strong> Leveraging Docker, Testcontainers ensures test consistency across diverse environments, including developers’ local machines, Continuous Integration (CI) servers, and production-like environments.</li><li><strong>Parallel Test Execution:</strong> Testcontainers facilitate parallel test execution by enabling each test or test suite to operate within its isolated container instance.</li><li><strong>Database State Management:</strong> With Test containers, database state management becomes effortless as it automatically resets the database state before and after each test, ensuring a clean slate for every test run.</li></ul><p><strong>4. Technology Stack</strong></p><p>The integration testing project employs the following technologies:</p><ul><li><strong><em>Java 17</em></strong></li><li><strong><em>Spring Boot 3</em></strong></li><li><strong><em>JUnit 5</em></strong></li><li><strong><em>Testcontainers</em></strong></li><li><strong><em>WebClient (for HTTP client testing)</em></strong></li><li><strong><em>Flyway</em></strong></li></ul><p>Install the required dependencies</p><pre> &lt;!-- https://mvnrepository.com/artifact/org.testcontainers/testcontainers --&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.testcontainers&lt;/groupId&gt;<br>            &lt;artifactId&gt;testcontainers&lt;/artifactId&gt;<br>            &lt;version&gt;1.19.7&lt;/version&gt;<br>            &lt;scope&gt;test&lt;/scope&gt;<br>        &lt;/dependency&gt;<br>        &lt;!-- https://mvnrepository.com/artifact/org.testcontainers/junit-jupiter --&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.testcontainers&lt;/groupId&gt;<br>            &lt;artifactId&gt;junit-jupiter&lt;/artifactId&gt;<br>            &lt;version&gt;1.19.7&lt;/version&gt;<br>            &lt;scope&gt;test&lt;/scope&gt;<br>        &lt;/dependency&gt;<br>        &lt;!-- https://mvnrepository.com/artifact/org.testcontainers/postgresql --&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.testcontainers&lt;/groupId&gt;<br>            &lt;artifactId&gt;postgresql&lt;/artifactId&gt;<br>            &lt;version&gt;1.19.7&lt;/version&gt;<br>            &lt;scope&gt;test&lt;/scope&gt;<br>        &lt;/dependency&gt;</pre><p><strong>Configuration for Testcontainers</strong></p><pre>package com.ems.employee_service.utils;<br><br>import org.flywaydb.core.Flyway;<br>import org.slf4j.Logger;<br>import org.slf4j.LoggerFactory;<br>import org.testcontainers.containers.PostgreSQLContainer;<br>import org.testcontainers.containers.output.Slf4jLogConsumer;<br>import org.testcontainers.containers.wait.strategy.Wait;<br>import org.testcontainers.utility.DockerImageName;<br><br>import java.nio.file.Path;<br>import java.nio.file.Paths;<br><br>public class TestContainerManager {<br>private static final Logger logger = LoggerFactory.getLogger(TestContainerManager.class);<br>    private static final String POSTGRES_VERSION = &quot;14&quot;; // Specify a specific version of PostgreSQL<br>    private static final DockerImageName POSTGRES_IMAGE = DockerImageName.parse(&quot;postgres:&quot; + POSTGRES_VERSION);<br>    private static final String DEFAULT_DATABASE_NAME = &quot;test&quot;;<br>    private static final String PASSWORD=&quot;test&quot;;<br><br>    private static PostgreSQLContainer&lt;?&gt; container;<br><br>    /**<br>     * Starts the PostgreSQL container if needed and executes database migration using Flyway.<br>     */<br>    public static synchronized void startContainerIfNeeded() {<br>        if (container == null || !container.isRunning()) {<br>            container = new PostgreSQLContainer&lt;&gt;(POSTGRES_IMAGE)<br>                    .withDatabaseName(DEFAULT_DATABASE_NAME)<br>                    .withPassword(PASSWORD)<br>                   // .withEnv(&quot;POSTGRES_PASSWORD&quot;, &quot;test&quot;) // Using environment variables for configuration<br>                    .withLogConsumer(new Slf4jLogConsumer(logger)); // Log container output<br><br>            container.start();<br>            container.waitingFor(Wait.forLogMessage(&quot;.*database system is ready to accept connections.*&quot;, 1)); // Wait for database to be ready<br>            migrateDatabase();<br>        }<br>    }<br><br>    /**<br>     * Migrates the database using Flyway.<br>     */<br>    private static void migrateDatabase() {<br>        Path migrationPath = Paths.get(&quot;src/test/resources/db/migration&quot;);<br>        Flyway flyway = Flyway.configure()<br>                .dataSource(getJdbcUrl(), &quot;test&quot;, getPassword()) // Using environment variables for configuration<br>                .locations(&quot;filesystem:&quot; + migrationPath.toAbsolutePath().toString())<br>                .load();<br>        flyway.migrate();<br>    }<br><br>    /**<br>     * Starts the PostgreSQL container if needed.<br>     */<br>    public static void startContainer() {<br>        startContainerIfNeeded();<br>    }<br><br>    /**<br>     * Stops the PostgreSQL container if running.<br>     */<br>    public static void stopContainer() {<br>        if (container != null &amp;&amp; container.isRunning()) {<br>            container.stop();<br>        }<br>    }<br><br>    /**<br>     * Retrieves the JDBC URL of the PostgreSQL container.<br>     *<br>     * @return JDBC URL<br>     */<br>    public static String getJdbcUrl() {<br>        startContainerIfNeeded();<br>        return container.getJdbcUrl();<br>    }<br><br>    /**<br>     * Retrieves the database name used in the container.<br>     *<br>     * @return database name<br>     */<br>    public static String getDatabaseName() {<br>        return DEFAULT_DATABASE_NAME;<br>    }<br><br>    /**<br>     * Retrieves the database username.<br>     *<br>     * @return database username<br>     */<br>    public static String getUsername() {<br>        return &quot;test&quot;;<br>    }<br><br>    /**<br>     * Retrieves the database password.<br>     *<br>     * @return database password<br>     */<br>    public static String getPassword() {<br>        return PASSWORD; // Returning empty string instead of the actual password<br>    }<br>}</pre><p><strong>Key Annotations and Configuration for Testcontainers</strong></p><p>In this project, a dedicated configuration class, TestContainerManager, orchestrates the Testcontainers lifecycle and database migration.</p><p><strong>TestContainerManager Class:</strong></p><p>The TestContainerManager class oversees the PostgreSQL container lifecycle and database migration through Flyway. Key methods include:</p><ul><li><strong>startContainerIfNeeded():</strong> Initiates the PostgreSQL container if it’s not already running, executing database migration using Flyway.</li><li><strong>migrateDatabase():</strong> Orchestrates database migration via Flyway, applying migration scripts located in the src/test/resources/db/migration directory.</li><li><strong>getJdbcUrl(), getDatabaseName(), getUsername(), and getPassword():</strong> Facilitate access to the container’s JDBC URL, database name, username, and password, respectively.</li></ul><p>Utilizing the<em> </em><strong><em>PostgreSQLContainer</em></strong><em> </em>from <strong><em>Testcontainers</em></strong>, along with <strong><em>Slf4jLogConsumer</em></strong> for logging container output, ensures efficient management of container instantiation and database migration logic.</p><p>By centralizing container management and database migration in a separate configuration class, the logic becomes reusable across multiple test classes, enhancing maintainability and code organization.</p><pre>package com.ems.employee_service.utils;<br><br>import java.util.UUID;<br><br>public class TestDataGenerator {<br><br>    public static String generateUniqueEmail(String name) {<br>        // Generate a random UUID and combine it with the employee&#39;s name to create a meaningful email address<br>        String uuid = UUID.randomUUID().toString().substring(0, 8); // Take a substring to shorten the UUID<br>        return name.toLowerCase().replace(&quot; &quot;, &quot;.&quot;) + &quot;.&quot; + uuid + &quot;@test.com&quot;;<br>    }<br><br>    public static String generateUniqueEmployeeId(){<br>        return UUID.randomUUID().toString().substring(0,8);<br>    }<br>}</pre><p><strong>Controller-Level Testing with TestContainers</strong></p><pre>package com.ems.employee_service.controller;<br>import com.ems.employee_service.dto.request.EmployeeRequest;<br>import com.ems.employee_service.entity.Employee;<br>import com.ems.employee_service.repository.EmployeeRepository;<br>import com.ems.employee_service.utils.TestContainerManager;<br>import com.ems.employee_service.utils.TestDataGenerator;<br>import jakarta.transaction.Transactional;<br>import org.junit.jupiter.api.*;<br>import org.slf4j.Logger;<br>import org.slf4j.LoggerFactory;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;<br>import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;<br>import org.springframework.boot.test.context.SpringBootTest;<br>import org.springframework.boot.test.web.server.LocalServerPort;<br>import org.springframework.http.MediaType;<br>import org.springframework.web.reactive.function.BodyInserters;<br>import org.springframework.web.reactive.function.client.WebClient;<br>import reactor.core.publisher.Mono;<br>import java.math.BigDecimal;<br>import java.util.Optional;<br>import static org.assertj.core.api.Assertions.assertThat;<br><br><br>@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)<br>@AutoConfigureMockMvc<br>@TestMethodOrder(MethodOrderer.OrderAnnotation.class)<br>@Transactional<br>@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)<br>class EmployeeTestContainerControllerTest {<br>    @LocalServerPort<br>    private int port;<br>    @Autowired<br>    private EmployeeRepository employeeRepository;<br><br>    @Autowired<br>    private WebClient.Builder webClientBuilder;<br><br>    private static final Logger logger = LoggerFactory.getLogger(EmployeeTestContainerControllerTest.class);<br><br>    @BeforeEach<br>    void setUp() {<br>        TestContainerManager.startContainer(); // Start the PostgreSQL container before each test<br>    }<br><br>    @AfterEach<br>    void tearDown() {<br>        TestContainerManager.stopContainer(); // Stop the PostgreSQL container after each test<br>    }<br><br>    @Test<br>    @Order(1)<br>    @DisplayName(&quot;Verify Add employee should return success and persist data in the database&quot;)<br>    void addEmployeeTest() throws Exception {<br>        // Set base URL for the WebClient<br>        String baseUrl = &quot;http://localhost:&quot; + port;<br>        WebClient webClient = webClientBuilder.baseUrl(baseUrl).build();<br><br>        // Given<br>        EmployeeRequest employeeRequest = createTestEmployeeRequest();<br>        employeeRequest.setEmail(TestDataGenerator.generateUniqueEmail(employeeRequest.getName()));<br>        employeeRequest.setEmployeeId(TestDataGenerator.generateUniqueEmployeeId());<br><br>        // When<br>        Mono&lt;Employee&gt; result = webClient<br>                .post()<br>                .uri(&quot;/api/v1/employee&quot;)<br>                .contentType(MediaType.APPLICATION_JSON)<br>                .body(BodyInserters.fromValue(employeeRequest))<br>                .retrieve()<br>                .bodyToMono(Employee.class);<br><br>        // Then<br>        Employee employee = result.block(); // Block until the result is available<br>        assertThat(employee).isNotNull();<br><br>        // Query the database to check if the employee data is persisted<br>        Optional&lt;Employee&gt; optionalEmployee = employeeRepository.findEmployeesByEmployeeId(employeeRequest.getEmployeeId());<br><br>        logger.info(&quot;Employee Details:&quot;+optionalEmployee);<br><br>        // Validate if the employee data exists in the database<br>        assertThat(optionalEmployee).isPresent();<br>        Employee persistedEmployee = optionalEmployee.get();<br><br>        // Validate if the attributes of the employee record match the posted data<br>        assertThat(persistedEmployee.getName()).isEqualTo(employeeRequest.getName());<br>        assertThat(persistedEmployee.getEmail()).isEqualTo(employeeRequest.getEmail());<br>        assertThat(persistedEmployee.getPosition()).isEqualTo(employeeRequest.getPosition());<br>        assertThat(persistedEmployee.getPhoneNumber()).isEqualTo(employeeRequest.getPhoneNumber());<br>        assertThat(persistedEmployee.getSalary()).isEqualByComparingTo(employeeRequest.getSalary());<br>        assertThat(persistedEmployee.getStatus()).isEqualTo(employeeRequest.getStatus());<br>    }<br><br>    private EmployeeRequest createTestEmployeeRequest() {<br>        return EmployeeRequest.builder()<br>                .employeeId(&quot;E12345&quot;)<br>                .name(&quot;John Doe&quot;)<br>                .email(&quot;john.doe@example.com&quot;)<br>                .position(&quot;Developer&quot;)<br>                .phoneNumber(&quot;123-456-7890&quot;)<br>                .salary(new BigDecimal(&quot;75000.00&quot;))<br>                .status(&quot;Active&quot;)<br>                .build();<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T4CianGgmUcQlyD5VfsAwQ.png" /></figure><p><strong>Understanding the Provided Code</strong></p><p>In the provided code snippet, WebClient is utilized, which is an optimal choice for testing reactive Spring Boot controllers. Here&#39;s a breakdown of the code&#39;s functionality:</p><ol><li><strong>Test Class Configuration:</strong></li></ol><ul><li>The <strong><em>EmployeeTestContainerControllerTest </em></strong>class is annotated with various Spring annotations such as <em>@SpringBootTest</em>, <em>@AutoConfigureMockMvc</em>, <em>@TestMethodOrder, @Transactional, and @AutoConfigureTestDatabase.</em> These annotations set up the test environment, enable transaction management, and configure the test database.</li></ul><p><strong>2. Container Management:</strong></p><ul><li>The <em>@BeforeEach</em> and <em>@AfterEach</em> methods are responsible for starting and stopping the PostgreSQL container before and after each test, respectively.</li><li><strong>Test Method:</strong></li><li>The <strong><em>addEmployeeTest</em></strong> method validates the functionality of adding a new employee to the system.</li><li><strong><em>WebClient</em></strong> is initialized with the base URL of the running application using <strong><em>@LocalServerPort and webClientBuilder.</em></strong></li><li>A test EmployeeRequest object is created with unique values for email and employeeId.</li><li>The webClient.post method sends a POST request to the <em>/api/v1/employee</em> endpoint with the EmployeeRequest object in the request body.</li><li>Assertions are made to ensure that the response contains a non-null Employee object.</li><li>The test queries the database using employeeRepository to verify if the employee data was persisted correctly.</li><li>Additional assertions validate that the persisted employee data matches the posted data.</li></ul><h3><strong>Conclusion</strong></h3><p>In summary, the combination of TestContainers, Spring Boot, and WebClient offers a robust and adaptable solution for comprehensive integration testing of reactive applications. It ensures that various components work seamlessly together and instills confidence in the application’s functionality and performance.</p><p><em>Enjoyed this? Smash the like button and follow me for more awesome content!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec0d7217f5cc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unit Testing at the Service Level]]></title>
            <link>https://medium.com/@abdirahman.bashir88/unit-testing-at-the-service-level-3a68d93a9485?source=rss-f47dde3fea3e------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a68d93a9485</guid>
            <dc:creator><![CDATA[Abdirahman Bashir Abdi]]></dc:creator>
            <pubDate>Sun, 18 Feb 2024 14:29:50 GMT</pubDate>
            <atom:updated>2024-02-18T14:29:50.936Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*bphhY9cIUqHzRIVQIeTZFA.jpeg" /></figure><p><strong>Introduction to Unit Testing at the Service Level</strong></p><p>Unit testing at the service level involves testing individual units of code within the service layer of an application. This layer typically contains business logic and interacts directly with data access layers, external services, or other components. Service-level unit tests focus on verifying the behavior of methods or functions within these service components in isolation from their dependencies.</p><p><strong>Technologies Used</strong></p><p>We’ll explore unit testing at the service level using Java and Spring Boot framework. We’ll utilize the following technologies:</p><ul><li><strong>JUnit 5</strong>: JUnit is a widely used testing framework for Java applications. JUnit 5 provides annotations and assertions for writing unit tests effectively.</li><li><strong>Mockito</strong>: Mockito is a popular mocking framework that allows us to create and configure mock objects for testing. It helps in isolating the code under test by mocking dependencies.</li><li><strong>AssertJ</strong>: AssertJ is a library for fluent assertions in Java. It provides a rich set of assertions that make our test cases more readable and expressive.</li></ul><p><strong>Source Code Availability and Prerequisites</strong></p><p>The complete source code for these tests can be found on <a href="https://github.com/Abdirahman143/advanced-rest-api.git"><strong><em>GitHub</em></strong></a>. Prerequisites include a basic setup of Spring Boot, familiarity with JUnit and Mockito, and Docker for database setup, ensuring a consistent testing environment.</p><p>Service Class Overview</p><p>Below is the service class (AccountServiceImpl) that we&#39;ll be testing:</p><pre>package com.example.advancedrestapi.service;<br><br>import com.example.advancedrestapi.customException.UserNotFoundException;<br>import com.example.advancedrestapi.mapper.AccountResponseMapper;<br>import com.example.advancedrestapi.model.Account;<br>import com.example.advancedrestapi.repository.AccountRepository;<br>import com.example.advancedrestapi.request.AccountPartialUpdateRequest;<br>import com.example.advancedrestapi.request.AccountRequest;<br>import com.example.advancedrestapi.response.AccountResponse;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.http.HttpStatus;<br>import org.springframework.http.ResponseEntity;<br>import org.springframework.stereotype.Service;<br><br>import java.util.List;<br>import java.util.Optional;<br><br>@Service<br>public class AccountServiceImpl implements AccountService {<br>    final private AccountRepository accountRepository;<br>    @Autowired<br>    public AccountServiceImpl(AccountRepository accountRepository) {<br>        this.accountRepository = accountRepository;<br>    }<br><br><br>    //saving account related data to database<br>    @Override<br>    public ResponseEntity&lt;Account&gt; addAccount(AccountRequest accountRequest) {<br>        Account account = new Account();<br>        account.setFirstName(accountRequest.getFirstName());<br>        account.setMiddleName(accountRequest.getMiddleName());<br>        account.setLastName(accountRequest.getLastName());<br>        account.setEmail(accountRequest.getEmail());<br>        account.setMobileNumber(accountRequest.getMobileNumber());<br>        account.setAccountNumber(accountRequest.getAccountNumber());<br>        account.setDateOfBirth(accountRequest.getDateOfBirth());<br><br>        return new ResponseEntity&lt;&gt;(accountRepository.save(account), HttpStatus.CREATED);<br><br>    }<br><br><br>    @Override<br>    //getting all account data<br>    public ResponseEntity&lt;List&lt;AccountResponse&gt;&gt; getAllAccounts() {<br>        List&lt;Account&gt; accountList = accountRepository.findAll();<br>        return new ResponseEntity&lt;&gt;(accountList.stream().<br>                map(AccountResponseMapper::MapToResponse).toList(),<br>                HttpStatus.FOUND);<br><br>    }<br><br><br>    //find employee details by email and account number<br>    @Override<br>    public Optional&lt;AccountResponse&gt; findAccountDetails(String accountNumber, String email) {<br>        Optional&lt;Account&gt; accountOptional = accountRepository.findAccountDetails(accountNumber, email);<br>        if (!accountOptional.isPresent()) {<br>            throw new UserNotFoundException(&quot;account number : &quot; + accountNumber + &quot; and email : &quot; + email + &quot;not found. Please try with a valid account number and email.&quot;);<br>        }<br>        Account account = accountOptional.get();<br>        AccountResponse accountResponse = AccountResponse<br>                .builder().<br>                id(account.getId()).<br>                firstName(account.getFirstName()).<br>                middleName(account.getMiddleName()).<br>                email(account.getEmail()).<br>                accountNumber(account.getAccountNumber()).<br>                mobileNumber(account.getMobileNumber()).<br>                build();<br>        return Optional.of(accountResponse);<br>    }<br><br>    //updating the account details<br>    @Override<br>    public ResponseEntity&lt;AccountResponse&gt; UpdateAccountDetails(AccountRequest accountRequest,<br>                                                                String accountNumber,<br>                                                                String email) {<br>        Optional&lt;Account&gt; accountOptional = accountRepository.findAccountDetails(accountNumber, email);<br>        if (!accountOptional.isPresent()) {<br>            throw new UserNotFoundException(&quot;account number : &quot; + accountNumber + &quot; and email : &quot; + email + &quot;not found. Please try with a valid account number and email.&quot;);<br>        }<br><br>        Account existingAccount = accountOptional.get();<br>        updateAccountDetails(existingAccount, accountRequest);<br>        Account updatedAccount = accountRepository.save(existingAccount);<br>        AccountResponse accountResponse = AccountResponseMapper.MapToResponse(updatedAccount);<br><br>        return new ResponseEntity&lt;&gt;(accountResponse, HttpStatus.OK);<br><br><br>    }<br><br>    //this method updates the account details<br>    public void updateAccountDetails(Account existingAccount, AccountRequest accountRequest) {<br>        existingAccount.setFirstName(accountRequest.getFirstName());<br>        existingAccount.setMiddleName(accountRequest.getMiddleName());<br>        existingAccount.setLastName(accountRequest.getLastName());<br>        existingAccount.setMobileNumber(accountRequest.getMobileNumber());<br>        existingAccount.setDateOfBirth(accountRequest.getDateOfBirth());<br>    }<br><br><br>//partial update the account details<br><br>    @Override<br>    public ResponseEntity&lt;AccountResponse&gt; updateAccountDetailsPartially(AccountPartialUpdateRequest partialUpdateRequest,<br>                                                                         String accountNumber,<br>                                                                         String email) {<br>        Optional&lt;Account&gt; accountOptional = accountRepository.findAccountDetails(accountNumber, email);<br>        if (!accountOptional.isPresent()) {<br>            throw new UserNotFoundException(&quot;account number : &quot; + accountNumber + &quot; and email : &quot; + email + &quot;not found. Please try with a valid account number and email.&quot;);<br>        }<br>        Account existingAccount = accountOptional.get();<br>        if (partialUpdateRequest.getMobileNumber() != null) {<br>            existingAccount.setMobileNumber(partialUpdateRequest.getMobileNumber());<br>        }<br>        if (partialUpdateRequest.getDateOfBirth() != null) {<br>            existingAccount.setDateOfBirth(partialUpdateRequest.getDateOfBirth());<br>        }<br>        Account updatedAccount = accountRepository.save(existingAccount);<br>        AccountResponse accountResponse = AccountResponseMapper.MapToResponse(updatedAccount);<br>        return new ResponseEntity&lt;&gt;(accountResponse, HttpStatus.OK);<br>    }<br><br>    //Delete account by account Number;<br>    @Override<br>    public ResponseEntity&lt;String&gt; deleteAccountDetails(String accountNumber, String email) {<br>        Optional&lt;Account&gt; accountOptional = accountRepository.findAccountDetails(accountNumber, email);<br>        if (!accountOptional.isPresent()) {<br>            throw new UserNotFoundException(&quot;account number : &quot; + accountNumber + &quot; and email : &quot; + email + &quot;not found. Please try with a valid account number and email.&quot;);<br>        }<br>        accountRepository.deleteByAccountNumber(accountNumber);<br>        return ResponseEntity.ok(&quot;Account with account number &quot; + accountNumber+&quot; has been permanently deleted.&quot;);<br><br>    }<br>}</pre><p>The AccountServiceImpl class is a service implementation responsible for managing account-related operations in a REST API. Here are the key areas and functionalities provided by this class:</p><ol><li><strong>Add Account</strong>: This method (addAccount) adds a new account to the database by saving the provided account details. It receives an AccountRequest object containing account information and returns a ResponseEntity with the created account and a HTTP status of CREATED.</li><li><strong>Get All Accounts</strong>: The getAllAccounts method retrieves all existing accounts from the database and maps them to AccountResponse objects using the AccountResponseMapper. It returns a ResponseEntity containing a list of account responses and a HTTP status of FOUND.</li><li><strong>Find Account Details</strong>: The findAccountDetails method retrieves account details based on the provided account number and email. If the account is found, it returns an Optional containing the account response; otherwise, it throws a UserNotFoundException.</li><li><strong>Update Account Details</strong>: This method (updateAccountDetails) updates the details of an existing account based on the provided account number and email. It receives an AccountRequest object with updated details and returns a ResponseEntity containing the updated account response and a HTTP status of OK.</li><li><strong>Partial Update Account Details</strong>: The updateAccountDetailsPartially method allows for partial updates of account details, such as updating the mobile number or date of birth. It receives a AccountPartialUpdateRequest object with partial updates and returns a ResponseEntity containing the updated account response and a HTTP status of OK.</li><li><strong>Delete Account</strong>: This method (deleteAccountDetails) deletes an account based on the provided account number and email. If the account exists, it deletes it from the database; otherwise, it throws a UserNotFoundException. It returns a ResponseEntity with a success message and a HTTP status of OK</li></ol><p><strong>TestDataProvider</strong></p><pre>package com.example.advancedrestapi.service;<br><br>import com.example.advancedrestapi.model.Account;<br>import com.example.advancedrestapi.request.AccountPartialUpdateRequest;<br>import com.example.advancedrestapi.request.AccountRequest;<br>import com.example.advancedrestapi.response.AccountResponse;<br><br>import java.time.LocalDate;<br>import java.time.ZoneId;<br>import java.util.Date;<br>import java.util.List;<br>import java.util.stream.Collectors;<br><br>public class TestDataDriver {<br><br>    public static Account createTestAccount() {<br>        LocalDate dob = LocalDate.of(1990, 1, 1);<br>        Date dateOfBirth = Date.from(dob.atStartOfDay(ZoneId.systemDefault()).toInstant());<br><br>        Account account = new Account();<br>        account.setFirstName(&quot;John&quot;);<br>        account.setMiddleName(&quot;Doe&quot;);<br>        account.setLastName(&quot;Smith&quot;);<br>        account.setEmail(&quot;john.smith@example.com&quot;);<br>        account.setMobileNumber(&quot;1234567890&quot;);<br>        account.setAccountNumber(&quot;123456789&quot;);<br>        account.setDateOfBirth(dateOfBirth);<br><br>        return account;<br>    }<br><br>    public static AccountRequest createTestAccountRequest() {<br>        LocalDate dob = LocalDate.of(1990, 1, 1);<br>        Date dateOfBirth = Date.from(dob.atStartOfDay(ZoneId.systemDefault()).toInstant());<br><br>        AccountRequest accountRequest = new AccountRequest();<br>        accountRequest.setFirstName(&quot;John&quot;);<br>        accountRequest.setMiddleName(&quot;Doe&quot;);<br>        accountRequest.setLastName(&quot;Smith&quot;);<br>        accountRequest.setEmail(&quot;john.smith@example.com&quot;);<br>        accountRequest.setMobileNumber(&quot;1234567890&quot;);<br>        accountRequest.setAccountNumber(&quot;123456789&quot;);<br>        accountRequest.setDateOfBirth(dateOfBirth);<br><br>        return accountRequest;<br>    }<br><br>    public static AccountResponse createTestAccountResponse() {<br>        LocalDate dob = LocalDate.of(1990, 1, 1); // Example date of birth<br>        Date dateOfBirth = Date.from(dob.atStartOfDay(ZoneId.systemDefault()).toInstant());<br><br>        AccountResponse accountResponse = AccountResponse.builder()<br>                .firstName(&quot;John&quot;)<br>                .middleName(&quot;Doe&quot;)<br>                .lastName(&quot;Smith&quot;)<br>                .email(&quot;john.smith@example.com&quot;)<br>                .mobileNumber(&quot;1234567890&quot;)<br>                .accountNumber(&quot;123456789&quot;)<br>                .dateOfBirth(dateOfBirth)<br>                .build();<br><br>        return accountResponse;<br>    }<br><br>    public static List&lt;Account&gt; createTestAccounts() {<br>        LocalDate dob1 = LocalDate.of(1990, 1, 1); // Example date of birth<br>        LocalDate dob2 = LocalDate.of(1991, 2, 2);<br>        LocalDate dob3 = LocalDate.of(1992, 3, 3);<br><br>        Account account1 = new Account();<br>        account1.setFirstName(&quot;John&quot;);<br>        account1.setMiddleName(&quot;Doe&quot;);<br>        account1.setLastName(&quot;Smith&quot;);<br>        account1.setEmail(&quot;john.smith@example.com&quot;);<br>        account1.setMobileNumber(&quot;1234567890&quot;);<br>        account1.setAccountNumber(&quot;123456789&quot;);<br>        account1.setDateOfBirth(Date.from(dob1.atStartOfDay(ZoneId.systemDefault()).toInstant()));<br><br>        Account account2 = new Account();<br>        account2.setFirstName(&quot;Alice&quot;);<br>        account2.setMiddleName(&quot;Jane&quot;);<br>        account2.setLastName(&quot;Doe&quot;);<br>        account2.setEmail(&quot;alice.doe@example.com&quot;);<br>        account2.setMobileNumber(&quot;9876543210&quot;);<br>        account2.setAccountNumber(&quot;987654321&quot;);<br>        account2.setDateOfBirth(Date.from(dob2.atStartOfDay(ZoneId.systemDefault()).toInstant()));<br><br>        Account account3 = new Account();<br>        account3.setFirstName(&quot;Bob&quot;);<br>        account3.setMiddleName(&quot;John&quot;);<br>        account3.setLastName(&quot;Smith&quot;);<br>        account3.setEmail(&quot;bob.smith@example.com&quot;);<br>        account3.setMobileNumber(&quot;4561237890&quot;);<br>        account3.setAccountNumber(&quot;456123789&quot;);<br>        account3.setDateOfBirth(Date.from(dob3.atStartOfDay(ZoneId.systemDefault()).toInstant()));<br><br>        return List.of(account1, account2, account3);<br>    }<br><br>    public static List&lt;AccountResponse&gt; createTestAccountResponses() {<br>        return createTestAccounts().stream()<br>                .map(account -&gt; AccountResponse.builder()<br>                        .firstName(account.getFirstName())<br>                        .middleName(account.getMiddleName())<br>                        .lastName(account.getLastName())<br>                        .email(account.getEmail())<br>                        .mobileNumber(account.getMobileNumber())<br>                        .accountNumber(account.getAccountNumber())<br>                        .dateOfBirth(account.getDateOfBirth())<br>                        .build())<br>                .collect(Collectors.toList());<br>    }<br><br>  public static AccountPartialUpdateRequest createPartialUpdateRequest() {<br><br>            LocalDate localDateOfBirth = LocalDate.now().minusYears(25);<br>            Date dateOfBirth = Date.from(localDateOfBirth.atStartOfDay(ZoneId.systemDefault()).toInstant());<br><br>            AccountPartialUpdateRequest partialUpdateRequest = new AccountPartialUpdateRequest();<br>            partialUpdateRequest.setMobileNumber(&quot;9876543210&quot;);<br>            partialUpdateRequest.setDateOfBirth(dateOfBirth);<br>            return partialUpdateRequest;<br>        }<br>    }<br></pre><h4>AccountServiceImplTest</h4><pre>package com.example.advancedrestapi.service;<br><br>import com.example.advancedrestapi.controller.TestDataProvider;<br>import com.example.advancedrestapi.customException.UserNotFoundException;<br>import com.example.advancedrestapi.mapper.AccountResponseMapper;<br>import com.example.advancedrestapi.model.Account;<br>import com.example.advancedrestapi.repository.AccountRepository;<br>import com.example.advancedrestapi.request.AccountPartialUpdateRequest;<br>import com.example.advancedrestapi.request.AccountRequest;<br>import com.example.advancedrestapi.response.AccountResponse;<br>import org.junit.jupiter.api.*;<br>import org.junit.jupiter.api.extension.ExtendWith;<br>import org.mockito.InjectMocks;<br>import org.mockito.Mock;<br>import org.mockito.junit.jupiter.MockitoExtension;<br>import org.slf4j.Logger;<br>import org.slf4j.LoggerFactory;<br>import org.springframework.http.HttpStatus;<br>import org.springframework.http.ResponseEntity;<br><br>import java.time.LocalDate;<br>import java.util.List;<br>import java.util.Optional;<br>import java.util.stream.Collectors;<br><br>import org.junit.jupiter.api.Test;<br><br>import static org.assertj.core.api.Assertions.assertThat;<br>import static org.assertj.core.api.AssertionsForClassTypes.tuple;<br>import static org.junit.jupiter.api.Assertions.*;<br>import static org.mockito.ArgumentMatchers.any;<br>import static org.mockito.Mockito.*;<br>import static org.mockito.Mockito.when;<br>@ExtendWith(MockitoExtension.class)<br>@TestMethodOrder(MethodOrderer.OrderAnnotation.class)<br>class AccountServiceImplTest {<br><br>    @Mock<br>    private AccountRepository accountRepository;<br><br>    @InjectMocks<br>    private AccountServiceImpl accountService;<br><br>    private Account account;<br>    private AccountRequest accountRequest;<br>    private AccountResponse accountResponse;<br>    static private final Logger logger = LoggerFactory.getLogger(AccountServiceImplTest.class);<br><br>    @BeforeEach<br>    void setUp() {<br>        LocalDate dob = LocalDate.now().minusYears(30);<br>        account = TestDataProvider.createAccount(&quot;John&quot;, &quot;John&quot;, &quot;1234567&quot;, &quot;John88@test.com&quot;, &quot;0710816522&quot;, dob);<br>        accountRequest = TestDataProvider.createAccountRequest(&quot;John&quot;, &quot;John&quot;, &quot;1234567&quot;, &quot;John88@test.com&quot;, &quot;0710816522&quot;, dob);<br><br>    }<br><br>    @Test<br>    @DisplayName(&quot;Verify that add account details with valid data return success!&quot;)<br>    @Order(1)<br>    void addAccount() {<br>        // Given<br>        when(accountRepository.save(any(Account.class))).thenReturn(account);<br><br><br>        // When<br>        ResponseEntity&lt;Account&gt; responseEntity = accountService.addAccount(accountRequest);<br><br>        // Then<br>        assertThat(responseEntity)<br>                .isNotNull()<br>                .hasFieldOrPropertyWithValue(&quot;statusCode&quot;, HttpStatus.CREATED)<br>                .extracting(ResponseEntity::getBody)<br>                .isEqualTo(account);<br><br>        //verify<br>        verify(accountRepository).save(any(Account.class));<br>    }<br><br><br>    @Test<br>    @DisplayName(&quot;Verify get all account details should return success&quot;)<br>    @Order(2)<br>    void getAllAccounts() {<br>        // Given<br>        List&lt;Account&gt; expectedAccounts = TestDataDriver.createTestAccounts();<br>        List&lt;AccountResponse&gt; expectedAccountResponses =  expectedAccounts.stream()<br>                .map(AccountResponseMapper::MapToResponse)<br>                .collect(Collectors.toList());<br><br>        when(accountRepository.findAll()).thenReturn(expectedAccounts);<br><br>        // When<br>        ResponseEntity&lt;List&lt;AccountResponse&gt;&gt; responseEntity = accountService.getAllAccounts();<br><br>        // Then<br>        assertThat(responseEntity)<br>                .isNotNull()<br>                .extracting(ResponseEntity::getStatusCode)<br>                .isEqualTo(HttpStatus.FOUND);<br><br>        assertThat(responseEntity.getBody())<br>                .isNotNull()<br>                .hasSize(expectedAccounts.size())<br>                .extracting(<br>                        AccountResponse::getFirstName,<br>                        AccountResponse::getMiddleName,<br>                        AccountResponse::getLastName,<br>                        AccountResponse::getAccountNumber,<br>                        AccountResponse::getMobileNumber,<br>                        AccountResponse::getEmail,<br>                        AccountResponse::getDateOfBirth<br>                )<br>                .containsExactlyElementsOf(expectedAccountResponses.stream()<br>                        .map(accountResponse -&gt;<br>                                tuple(<br>                                        accountResponse.getFirstName(),<br>                                        accountResponse.getMiddleName(),<br>                                        accountResponse.getLastName(),<br>                                        accountResponse.getAccountNumber(),<br>                                        accountResponse.getMobileNumber(),<br>                                        accountResponse.getEmail(),<br>                                        accountResponse.getDateOfBirth()<br>                                )<br>                        )<br>                        .toList()<br>                );<br>    }<br><br>    @Test<br>    @DisplayName(&quot;Verify find account details should return account response&quot;)<br>    @Order(3)<br>    void findAccountDetails_ShouldReturnAccountResponse() {<br>        // Given<br>        String accountNumber = &quot;123456789&quot;;<br>        String email = &quot;john.smith@example.com&quot;;<br>        Account testAccount = TestDataDriver.createTestAccount();<br>        when(accountRepository.findAccountDetails(accountNumber, email)).thenReturn(Optional.of(testAccount));<br><br>        // When<br>        Optional&lt;AccountResponse&gt; optionalAccountResponse = accountService.findAccountDetails(accountNumber, email);<br><br>        // Then<br>         assertThat(optionalAccountResponse).isPresent();<br>        AccountResponse accountResponse = optionalAccountResponse.get();<br>        assertThat(accountResponse.getFirstName()).isEqualTo(testAccount.getFirstName());<br>        assertThat(accountResponse.getEmail()).isEqualTo(testAccount.getEmail());<br>        assertThat(accountResponse.getAccountNumber()).isEqualTo(testAccount.getAccountNumber());<br>        assertThat(accountResponse.getMobileNumber()).isEqualTo(testAccount.getMobileNumber());<br><br><br>        //verify<br>        verify(accountRepository).findAccountDetails(accountNumber,email);<br><br><br>    }<br><br>    @Test<br>    @DisplayName(&quot;Verify find account details with invalid account should throw exception&quot;)<br>    @Order(4)<br>    void findAccountDetails_WithInvalidAccount_ShouldThrowUserNotFoundException() {<br>        // Given<br>        String accountNumber = &quot;invalidAccount&quot;;<br>        String email = &quot;invalidEmail&quot;;<br><br>        // When<br>        when(accountRepository.findAccountDetails(accountNumber, email)).thenReturn(Optional.empty());<br><br>        // Then<br>        assertThrows(UserNotFoundException.class, () -&gt; {<br>            accountService.findAccountDetails(accountNumber, email);<br>        });<br><br>        //verify<br>        verify(accountRepository).findAccountDetails(accountNumber,email);<br>    }<br><br>    @Test<br>    @DisplayName(&quot;Verify update account details should return updated account response&quot;)<br>    @Order(5)<br>    void updateAccountDetails_ShouldReturnUpdatedAccountResponse() {<br>        // Given<br>        String accountNumber = &quot;123456789&quot;;<br>        String email = &quot;john.smith@example.com&quot;;<br>        AccountRequest updatedAccountRequest = TestDataDriver.createTestAccountRequest();<br>        Account existingAccount = TestDataDriver.createTestAccount();<br>        when(accountRepository.findAccountDetails(accountNumber, email)).thenReturn(Optional.of(existingAccount));<br>        when(accountRepository.save(any(Account.class))).thenReturn(existingAccount);<br>        // When<br>        ResponseEntity&lt;AccountResponse&gt; responseEntity = accountService.UpdateAccountDetails(updatedAccountRequest, accountNumber, email);<br><br>        // Then<br>        assertThat(responseEntity.getStatusCode()).isEqualTo(HttpStatus.OK);<br>        AccountResponse updatedAccountResponse = responseEntity.getBody();<br>        assertThat(updatedAccountResponse).isNotNull();<br>        assertThat(updatedAccountResponse.getFirstName()).isEqualTo(updatedAccountRequest.getFirstName());<br>        assertThat(updatedAccountResponse.getMiddleName()).isEqualTo(updatedAccountRequest.getMiddleName());<br>        assertThat(updatedAccountResponse.getMobileNumber()).isEqualTo(updatedAccountRequest.getMobileNumber());<br>        assertThat(updatedAccountResponse.getDateOfBirth()).isEqualTo(updatedAccountRequest.getDateOfBirth());<br><br>        //verify<br>        verify(accountRepository,times(1)).save(any(Account.class));<br>        verify(accountRepository,times(1)).findAccountDetails(accountNumber,email);<br><br>    }<br><br>    @Test<br>    @DisplayName(&quot;Verify update account details with invalid account should throw exception&quot;)<br>    @Order(6)<br>    void updateAccountDetails_WithInvalidAccount_ShouldThrowUserNotFoundException() {<br>        // Given<br>        String accountNumber = &quot;invalidAccount&quot;;<br>        String email = &quot;invalidEmail&quot;;<br>        AccountRequest updatedAccountRequest = TestDataDriver.createTestAccountRequest();<br>        when(accountRepository.findAccountDetails(accountNumber, email)).thenReturn(Optional.empty());<br><br>        // When, Then<br>        assertThrows(UserNotFoundException.class, () -&gt; {<br>            accountService.UpdateAccountDetails(updatedAccountRequest, accountNumber, email);<br>        });<br><br>        //verify<br>        verify(accountRepository,times(1)).findAccountDetails(accountNumber,email);<br>        verify(accountRepository,never()).save(any(Account.class));<br>    }<br><br>    @Test<br>    @DisplayName(&quot;Verify partial update account details should return updated account response&quot;)<br>    @Order(7)<br>    void updateAccountDetailsPartially_ShouldReturnUpdatedAccountResponse() {<br>        // Given<br>        String accountNumber = &quot;123456789&quot;;<br>        String email = &quot;john.smith@example.com&quot;;<br>        AccountPartialUpdateRequest partialUpdateRequest = TestDataDriver.createPartialUpdateRequest();<br>        Account existingAccount = TestDataDriver.createTestAccount();<br>        when(accountRepository.findAccountDetails(accountNumber, email)).thenReturn(Optional.of(existingAccount));<br>        when(accountRepository.save(any(Account.class))).thenReturn(existingAccount);<br><br>        // When<br>        ResponseEntity&lt;AccountResponse&gt; responseEntity = accountService.updateAccountDetailsPartially(partialUpdateRequest, accountNumber, email);<br><br>        // Then<br>        assertThat(responseEntity.getStatusCode()).isEqualTo(HttpStatus.OK);<br>        AccountResponse updatedAccountResponse = responseEntity.getBody();<br>        assertThat(updatedAccountResponse).isNotNull();<br>        assertThat(updatedAccountResponse.getMobileNumber()).isEqualTo(partialUpdateRequest.getMobileNumber());<br>        assertThat(updatedAccountResponse.getDateOfBirth()).isEqualTo(partialUpdateRequest.getDateOfBirth());<br><br>        //verify<br>        verify(accountRepository).findAccountDetails(accountNumber,email);<br>        verify(accountRepository,times(1)).save(any(Account.class));<br><br>    }<br><br>    @Test<br>    @DisplayName(&quot;Verify partial update account details with invalid account should throw exception&quot;)<br>    @Order(8)<br>    void updateAccountDetailsPartially_WithInvalidAccount_ShouldThrowUserNotFoundException() {<br>        // Given<br>        String accountNumber = &quot;invalidAccount&quot;;<br>        String email = &quot;invalidEmail&quot;;<br>        AccountPartialUpdateRequest partialUpdateRequest = TestDataDriver.createPartialUpdateRequest();<br>        when(accountRepository.findAccountDetails(accountNumber, email)).thenReturn(Optional.empty());<br><br>        // When, Then<br>        assertThrows(UserNotFoundException.class, () -&gt; {<br>            accountService.updateAccountDetailsPartially(partialUpdateRequest, accountNumber, email);<br>        });<br><br>        //verify<br>        verify(accountRepository,never()).save(any(Account.class));<br>        verify(accountRepository,times(1)).findAccountDetails(accountNumber,email);<br>    }<br><br>    @Test<br>    @DisplayName(&quot;Verify delete account should return success message&quot;)<br>    @Order(9)<br>    void deleteAccountDetails_ShouldReturnSuccessMessage() {<br>        // Given<br>        String accountNumber = &quot;123456789&quot;;<br>        String email = &quot;john.smith@example.com&quot;;<br>        Account existingAccount = TestDataDriver.createTestAccount();<br>        when(accountRepository.findAccountDetails(accountNumber, email)).thenReturn(Optional.of(existingAccount));<br><br>        // When<br>        ResponseEntity&lt;String&gt; responseEntity = accountService.deleteAccountDetails(accountNumber, email);<br><br>        // Then<br>        assertThat(responseEntity.getStatusCode()).isEqualTo(HttpStatus.OK);<br>        assertThat(responseEntity.getBody()).isEqualTo(&quot;Account with account number &quot; + accountNumber + &quot; has been permanently deleted.&quot;);<br><br>        // Verify that deleteByAccountNumber method is called<br>        verify(accountRepository, times(1)).deleteByAccountNumber(accountNumber);<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OgR1PasjSE4uRbyG-bGXVQ.png" /></figure><h4>Mockito Keywords:</h4><ol><li><strong>when</strong>: Used to define the behavior of mocked methods. It specifies what the mocked object should return when a particular method is called with specific arguments.</li><li><strong>thenReturn</strong>: Specifies the value that should be returned by a mocked method when it’s called with the specified arguments.</li><li><strong>verify</strong>: Verifies that a method on a mocked object has been called with specific arguments and how many times it has been called.</li><li><strong>any</strong>: Matches any argument of the specified type. It’s often used in combination with when to specify behavior for any argument of a certain type.</li><li><strong>times</strong>: Specifies the exact number of times a method should be called during the test.</li><li><strong>never</strong>: Ensures that a method on a mocked object should never be called.</li></ol><h4>AssertJ Keywords:</h4><ol><li><strong>assertThat</strong>: Begins the assertion chain. It’s used to start an assertion on a particular object.</li><li><strong>isNotNull</strong>: Asserts that the object is not null.</li><li><strong>isEqualTo</strong>: Asserts that the object is equal to the expected value.</li><li><strong>isPresent</strong>: Asserts that an Optional object contains a value.</li><li><strong>extracting</strong>: Extracts properties or fields from objects to perform assertions on them.</li><li><strong>containsExactlyElementsOf</strong>: Asserts that the elements of one collection are exactly equal to the elements of another collection, regardless of order.</li><li><strong>tuple</strong>: Creates a tuple of values for comparison.</li><li><strong>assertThrows</strong>: Asserts that a specific type of exception is thrown by the code under test.</li></ol><h4>JUnit Keywords:</h4><ol><li><strong>@Test</strong>: Annotation used to mark a method as a test method.</li><li><strong>@BeforeEach</strong>: Annotation used to specify that a method should be run before each test method in the class. It’s typically used to set up common test data or initialize objects.</li><li><strong>@DisplayName</strong>: Annotation used to provide a custom display name for a test method. It’s used for better readability of the test results.</li><li><strong>@Order</strong>: Annotation used to specify the order in which test methods should be executed. It’s useful when the order of test execution matters.</li><li><strong>assertThrows</strong>: Method provided by JUnit to assert that a specific type of exception is thrown by the code under test.</li></ol><h4><strong>Summary</strong></h4><p>In summary, the service-level testing conducted for the provided code base is thorough and well-structured, employing Mockito, AssertJ, and JUnit frameworks effectively. It ensures comprehensive testing coverage of various scenarios within the AccountServiceImpl class, enhancing the reliability and maintainability of the codebase.</p><p>For a comprehensive understanding of controller-level testing in Spring Boot, you can refer to the following article: <a href="https://medium.com/@abdirahman.bashir88/comprehensive-controller-level-testing-in-spring-boot-a-professional-insight-342b5d096973">Comprehensive Controller-Level Testing in Spring Boot: A Professional Insight</a>. This article likely covers topics such as mocking HTTP requests, testing request mappings, handling request and response bodies, and verifying controller behavior. By combining service-level and controller-level testing, developers can ensure robust testing coverage across different layers of the application, leading to more reliable software.</p><p><em>Don’t forget to like and follow the article to stay updated with the latest insights on Spring Boot! Your support is greatly appreciated.</em></p><p>#java #springboot #Unit testing #integration testing</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a68d93a9485" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Comprehensive Controller Level Testing in Spring Boot: A Professional Insight]]></title>
            <link>https://medium.com/@abdirahman.bashir88/comprehensive-controller-level-testing-in-spring-boot-a-professional-insight-342b5d096973?source=rss-f47dde3fea3e------2</link>
            <guid isPermaLink="false">https://medium.com/p/342b5d096973</guid>
            <dc:creator><![CDATA[Abdirahman Bashir Abdi]]></dc:creator>
            <pubDate>Sat, 03 Feb 2024 12:33:49 GMT</pubDate>
            <atom:updated>2024-02-18T19:38:28.800Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/218/1*JjiBhjE3eUYweG0IGye0cA.jpeg" /></figure><h4>Summary</h4><p>Controller-level testing is crucial in ensuring the reliability and stability of RESTful APIs in Spring Boot applications. This article provides an in-depth look at a professional approach to testing a controller class, focusing on effective strategies and tools to achieve comprehensive test coverage.</p><h4>Unit Testing and Mocking</h4><p>Unit testing isolates individual components, ensuring they function as expected. In Spring Boot, controller testing typically involves sending simulated HTTP requests and asserting responses. Mocking is an integral part of this, allowing the simulation of service layer interactions without relying on actual database calls. This approach ensures speed and isolation, key aspects of effective unit testing.</p><h4>Technology Stack</h4><ul><li><strong>JUnit</strong>: The most popular Java testing framework, JUnit, is used for writing and running repeatable tests.</li><li><strong>Mockito</strong>: A mocking framework that efficiently creates and configures mock objects.</li><li><strong>AssertJ and Hamcrest</strong>: Libraries providing fluent assertion methods and matchers, enhancing the readability and expressiveness of tests.</li></ul><h4>Test Coverage</h4><p>Comprehensive test coverage includes:</p><ol><li><strong>Positive Tests</strong>: Validate the controller’s expected behavior under normal conditions. Example: Adding a new account with valid data.</li><li><strong>Negative Tests</strong>: Ensure the controller handles incorrect or invalid inputs correctly. Example: Attempts to add an account with duplicate email.</li><li><strong>Exception Handling Tests</strong>: Confirm that the controller appropriately handles and responds to exceptions. Example: Handling UserNotFoundException.</li></ol><h4>Documentation of Test Cases</h4><p>Each test case is meticulously documented, explaining the scenario being tested, the setup (Arrange), the action (Act), and the assertions (Assert). This clarity assists in future maintenance and understanding of the purpose and behavior of each test.</p><h4>Source Code Availability and Prerequisites</h4><p>The complete source code for these tests can be found on <a href="https://github.com/Abdirahman143/advanced-rest-api.git"><strong><em>GitHub</em></strong></a>. Prerequisites include a basic setup of Spring Boot, familiarity with JUnit and Mockito, and Docker for database setup, ensuring a consistent testing environment.</p><p><strong>RestController Class</strong></p><pre>package com.example.advancedrestapi.controller;<br><br>import com.example.advancedrestapi.customException.UserNotFoundException;<br>import com.example.advancedrestapi.model.Account;<br>import com.example.advancedrestapi.request.AccountPartialUpdateRequest;<br>import com.example.advancedrestapi.request.AccountRequest;<br>import com.example.advancedrestapi.response.AccountResponse;<br>import com.example.advancedrestapi.service.AccountService;<br>import io.swagger.v3.oas.annotations.Operation;<br>import io.swagger.v3.oas.annotations.media.Content;<br>import io.swagger.v3.oas.annotations.media.Schema;<br>import io.swagger.v3.oas.annotations.responses.ApiResponse;<br>import io.swagger.v3.oas.annotations.responses.ApiResponses;<br>import jakarta.persistence.GeneratedValue;<br>import jakarta.validation.Valid;<br>import org.springframework.data.repository.query.Param;<br>import org.springframework.http.ResponseEntity;<br>import org.springframework.web.bind.annotation.*;<br><br>import java.util.List;<br>import java.util.Optional;<br><br>@RestController<br>@RequestMapping(&quot;/api/v1/accounts&quot;)<br>//@BasePathAwareController<br>public class AccountController {<br><br>    private final AccountService accountService;<br><br>    public AccountController(AccountService accountService) {<br>        this.accountService = accountService;<br>    }<br><br><br>    //adding account details to database<br><br>                   @PostMapping()<br>                   @Operation(summary = &quot;add account info&quot;)<br>                   @ApiResponses(value = {<br>                           @ApiResponse(<br>                                   responseCode = &quot;201&quot;,<br>                                   description = &quot;Account details created!&quot;,<br>                                   content = {<br>                                           @Content(mediaType = &quot;application/json&quot;,<br>                                                   schema = @Schema(implementation = AccountResponse.class)<br>                                           )<br>                                   }<br>                           ),<br>                           @ApiResponse(responseCode = &quot;400&quot;,description = &quot;invalid Inputs!!&quot;)<br>                   })<br>    public ResponseEntity&lt;Account&gt;Save(@Valid @RequestBody  AccountRequest accountRequest){<br>        return accountService.addAccount(accountRequest);<br>    }<br><br><br>    @GetMapping()<br>    public ResponseEntity&lt;List&lt;AccountResponse&gt;&gt;getAccounts(){<br>        return accountService.getAllAccounts();<br>    }<br><br><br>    //get Accounts details by account number and email<br><br>    @GetMapping(&quot;/details&quot;)<br>    public Optional&lt;AccountResponse&gt;getAccountDetails(@RequestParam(required = true)String accountNumber,<br>                                                      @RequestParam(required = true)String email){<br>        return accountService.findAccountDetails(accountNumber,email);<br>    }<br><br>    //update account details<br><br>    @PutMapping(&quot;/{accountNumber}/{email}&quot;)<br>    public ResponseEntity&lt;AccountResponse&gt;updateAccountDetails(@Valid @RequestBody  AccountRequest accountRequest,<br>                                                               @PathVariable String accountNumber,<br>                                                               @PathVariable String email)throws UserNotFoundException{<br>        return  accountService.UpdateAccountDetails(accountRequest,accountNumber,email);<br><br>    }<br><br>    @PatchMapping(&quot;/partial/{accountNumber}/{email}&quot;)<br>    public ResponseEntity&lt;AccountResponse&gt;updateAccountPartially(<br>            @RequestBody @Valid<br>            AccountPartialUpdateRequest partialUpdateRequest,<br>            @PathVariable String accountNumber,<br>            @PathVariable String email)throws UserNotFoundException{<br>        return accountService.updateAccountDetailsPartially(partialUpdateRequest,accountNumber,email);<br>    }<br><br>//Delete account<br>    @DeleteMapping(&quot;/{accountNumber}/{email}&quot;)<br>    public ResponseEntity&lt;String&gt; deleteAccountDetails(@PathVariable String accountNumber,<br>                                                       @PathVariable String email)throws UserNotFoundException{<br>        return accountService.deleteAccountDetails(accountNumber,email);<br>    }<br><br>}</pre><p>The AccountController class in the com.example.advancedrestapi.controller package is a REST controller that manages account-related operations in a Spring Boot application. It leverages the AccountService to perform CRUD operations and interacts with clients via HTTP requests and responses.</p><h4>Constructor</h4><ul><li><strong>AccountController(AccountService accountService)</strong>: Initializes the controller with an instance of AccountService to handle business logic.</li></ul><h4>Endpoints</h4><p><strong>a. Add Account</strong></p><ul><li><strong>Endpoint</strong>: POST /api/v1/accounts</li><li><strong>Description</strong>: Adds new account details to the database.</li><li><strong>Request Body</strong>: Accepts an AccountRequest object containing the account details to be added. The request body must be valid as per the constraints defined in the AccountRequest class.</li><li><strong>Responses</strong>:</li><li>201 Created: Successfully created the account details. Returns the created Account object.</li><li>400 Bad Request: The request has invalid inputs.</li></ul><p><strong>b. Get All Accounts</strong></p><ul><li><strong>Endpoint</strong>: GET /api/v1/accounts</li><li><strong>Description</strong>: Retrieves a list of all account details from the database.</li><li><strong>Response</strong>: Returns a list of AccountResponse objects containing account details.</li></ul><ol><li><strong>Get Account Details</strong></li></ol><ul><li><strong>Endpoint</strong>: GET /api/v1/accounts/details</li><li><strong>Description</strong>: Retrieves the details of an account using the account number and email as search criteria.</li><li><strong>Parameters</strong>:</li><li>accountNumber (required): The account number of the account to retrieve.</li><li>email (required): The email associated with the account to retrieve.</li><li><strong>Response</strong>: Returns an AccountResponse object with the account details if found.</li></ul><p><strong>c. Update Account Details</strong></p><ul><li><strong>Endpoint</strong>: PUT /api/v1/accounts/{accountNumber}/{email}</li><li><strong>Description</strong>: Updates the account details for the specified account number and email.</li><li><strong>Path Variables</strong>:</li><li>accountNumber: The account number of the account to update.</li><li>email: The email associated with the account to update.</li><li><strong>Request Body</strong>: Accepts an AccountRequest object with the updated account details. The request body must be valid as per the constraints defined in the AccountRequest class.</li><li><strong>Response</strong>: Returns the updated AccountResponse object.</li></ul><p><strong>d. Partial Update of Account Details</strong></p><ul><li><strong>Endpoint</strong>: PATCH /api/v1/accounts/partial/{accountNumber}/{email}</li><li><strong>Description</strong>: Partially updates the account details for the specified account number and email.</li><li><strong>Path Variables</strong>:</li><li>accountNumber: The account number of the account to update.</li><li>email: The email associated with the account to update.</li><li><strong>Request Body</strong>: Accepts an AccountPartialUpdateRequest object with the fields to update.</li><li><strong>Response</strong>: Returns the updated AccountResponse object.</li></ul><p><strong>e. Delete Account</strong></p><ul><li><strong>Endpoint</strong>: DELETE /api/v1/accounts/{accountNumber}/{email}</li><li><strong>Description</strong>: Deletes the account details for the specified account number and email.</li><li><strong>Path Variables</strong>:</li><li>accountNumber: The account number of the account to delete.</li><li>email: The email associated with the account to delete.</li><li><strong>Response</strong>: Returns a confirmation message upon successful deletion.</li></ul><p><strong>TestDataProvider Class</strong></p><pre>package com.example.advancedrestapi.controller;<br><br>import com.example.advancedrestapi.model.Account;<br>import com.example.advancedrestapi.request.AccountRequest;<br>import com.example.advancedrestapi.response.AccountResponse;<br><br>import java.time.LocalDate;<br>import java.time.ZoneId;<br>import java.util.Date;<br>import java.util.List;<br><br>public class TestDataProvider {<br><br>    public static Account createAccount(String firstName, String lastName, String accountNumber, String email, String mobileNumber, LocalDate dob) {<br>        return Account.builder()<br>                .firstName(firstName)<br>                .lastName(lastName)<br>                .accountNumber(accountNumber)<br>                .email(email)<br>                .mobileNumber(mobileNumber)<br>                .dateOfBirth(Date.from(dob.atStartOfDay(ZoneId.systemDefault()).toInstant()))<br>                .build();<br>    }<br><br>    public static AccountRequest createAccountRequest(String firstName, String lastName, String accountNumber, String email, String mobileNumber, LocalDate dob) {<br>        return AccountRequest.builder()<br>                .firstName(firstName)<br>                .lastName(lastName)<br>                .accountNumber(accountNumber)<br>                .email(email)<br>                .mobileNumber(mobileNumber)<br>                .dateOfBirth(Date.from(dob.atStartOfDay(ZoneId.systemDefault()).toInstant()))<br>                .build();<br>    }<br><br>public static List&lt;AccountResponse&gt; createTestAccountResponses() {<br>      //arrange<br>      LocalDate localDateOfBirth = LocalDate.now().minusYears(23);<br>      // Convert LocalDate to Date<br>      Date dateOfBirth = Date.from(localDateOfBirth.atStartOfDay(ZoneId.systemDefault()).toInstant());<br>             return List.of(<br>                     AccountResponse.<br>                     builder().<br>                             firstName(&quot;Noor&quot;).<br>                             middleName(&quot;Dalaac&quot;).<br>                             lastName(&quot;Kahin&quot;).<br>                             accountNumber(&quot;345678900&quot;).<br>                             mobileNumber(&quot;0700816522&quot;).<br>                             email(&quot;kahin.abdi@test.com&quot;).<br>                             dateOfBirth(dateOfBirth).<br>                             build(),<br>                     AccountResponse.<br>                             builder().<br>                             firstName(&quot;shukri&quot;).<br>                             middleName(&quot;shafi&quot;).<br>                             lastName(&quot;Sahal&quot;).<br>                             accountNumber(&quot;31245678&quot;).<br>                             mobileNumber(&quot;070090053&quot;).<br>                             email(&quot;sahal.shakir@test.com&quot;).<br>                             dateOfBirth(dateOfBirth).<br>                             build(),<br>                     AccountResponse.<br>                             builder().<br>                             firstName(&quot;Abdi&quot;).<br>                             middleName(&quot;Abdirahman&quot;).<br>                             lastName(&quot;Abdi&quot;).<br>                             accountNumber(&quot;345678&quot;).<br>                             mobileNumber(&quot;070091653&quot;).<br>                             email(&quot;bashir.abdi@test.com&quot;).<br>                             dateOfBirth(dateOfBirth).<br>                             build());<br>    }<br>}</pre><p>It provides static methods to generate instances of Account, AccountRequest, and AccountResponse with pre-filled data. These methods simplify the process of setting up test scenarios by avoiding repetitive code for object creation across different test cases.</p><ul><li>createAccount(...): Generates an Account model object, useful for simulating database entities or objects that would be manipulated by service methods.</li><li>createAccountRequest(...): Creates an AccountRequest object that mimics client requests, ideal for testing controller request handling.</li><li>createTestAccountResponses(): Returns a list of AccountResponse objects, representing the expected responses that would be sent back to the client, ensuring that tests can verify the correctness of response data.</li></ul><p><strong>AccountControllerTest class</strong></p><ol><li><strong>Add Account Details</strong>: Verifies success on adding valid account details.</li><li><strong>Add Account Details with Empty Required Fields</strong>: Checks for error response when required fields are missing.</li><li><strong>Add Account Details with Invalid Email Format</strong>: Tests error handling for submitting an account with an invalid email format.</li><li><strong>Add Account Details with Invalid Phone Number and Future DOB</strong>: Validates error response for invalid phone numbers and future dates of birth.</li><li><strong>Add Account with Duplicate Account Number</strong>: Ensures duplicate account numbers trigger an error response.</li><li><strong>Add Account with Duplicate Email</strong>: Confirms adding an account with a duplicate email results in an error.</li><li><strong>Get All Account Details</strong>: Tests successful retrieval of all account details.</li><li><strong>Get Account Details with Valid Account Number and Email</strong>: Verifies fetching account details with valid identifiers succeeds.</li><li><strong>Get Account Details with Invalid Account Number and Email</strong>: Checks error handling when fetching details with invalid identifiers.</li><li><strong>Update Account Details with Valid Data</strong>: Confirms successful update with valid account details.</li><li><strong>Update Account Details with Invalid Data</strong>: Tests error response when updating with invalid identifiers.</li><li><strong>Partial Update Account Details with Valid Data</strong>: Verifies success on partially updating account details with valid data.</li><li><strong>Partial Update Account Details with Invalid Email or Account Number</strong>: Ensures error on partial updates with invalid identifiers.</li><li><strong>Delete Account Details with Valid Account Number and Email</strong>: Confirms successful deletion of account details with valid identifiers.</li></ol><p><strong>AccountControllerTest Class</strong></p><pre>package com.example.advancedrestapi.controller;<br><br>import com.example.advancedrestapi.customException.CustomizedExceptionHandler;<br>import com.example.advancedrestapi.customException.UserNotFoundException;<br>import com.example.advancedrestapi.model.Account;<br>import com.example.advancedrestapi.request.AccountPartialUpdateRequest;<br>import com.example.advancedrestapi.request.AccountRequest;<br>import com.example.advancedrestapi.response.AccountResponse;<br>import com.example.advancedrestapi.service.AccountService;<br>import com.fasterxml.jackson.core.JsonProcessingException;<br>import com.fasterxml.jackson.databind.ObjectMapper;<br>import com.jayway.jsonpath.DocumentContext;<br>import com.jayway.jsonpath.JsonPath;<br>import org.hamcrest.Matchers;<br>import org.junit.jupiter.api.*;<br>import org.junit.jupiter.api.extension.ExtendWith;<br>import org.mockito.InjectMocks;<br>import org.mockito.Mock;<br>import org.mockito.junit.jupiter.MockitoExtension;<br>import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;<br>import org.springframework.dao.DataIntegrityViolationException;<br>import org.springframework.http.HttpStatus;<br>import org.springframework.http.MediaType;<br>import org.springframework.http.ResponseEntity;<br>import org.springframework.test.web.servlet.MockMvc;<br>import org.springframework.test.web.servlet.MvcResult;<br>import org.springframework.test.web.servlet.ResultMatcher;<br>import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;<br>import org.springframework.test.web.servlet.setup.MockMvcBuilders;<br>import org.springframework.web.bind.MethodArgumentNotValidException;<br><br>import java.math.BigDecimal;<br>import java.time.LocalDate;<br>import java.time.ZoneId;<br>import java.util.Arrays;<br>import java.util.Date;<br>import java.util.List;<br>import java.util.Optional;<br><br>import static org.hamcrest.Matchers.containsInAnyOrder;<br>import static org.hamcrest.Matchers.hasSize;<br>import static org.junit.jupiter.api.Assertions.*;<br>import static org.mockito.ArgumentMatchers.any;<br>import static org.mockito.Mockito.*;<br>import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;<br>import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;<br>import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;<br><br><br>@ExtendWith(MockitoExtension.class)<br>@TestMethodOrder(MethodOrderer.OrderAnnotation.class)<br>class AccountControllerTest {<br><br>    @Mock<br>    private AccountService accountService;<br><br>    @InjectMocks<br>    private AccountController accountController;<br><br>    private MockMvc mockMvc;<br>    private Account account;<br>    private AccountRequest accountRequest;<br>    private AccountResponse accountResponse;<br>    private ObjectMapper objectMapper;<br><br>    @BeforeEach<br>    public void setUp(){<br><br>        CustomizedExceptionHandler customizedExceptionHandler = new CustomizedExceptionHandler();<br><br>        mockMvc = MockMvcBuilders.<br>                standaloneSetup(accountController).<br>                setControllerAdvice(customizedExceptionHandler). //register custom exception handling<br>                build();<br><br>        objectMapper= new ObjectMapper();<br>        LocalDate dob = LocalDate.now().minusYears(30);<br>        account = TestDataProvider.createAccount(&quot;Abdirahman&quot;, &quot;Abdi&quot;, &quot;1234567&quot;, &quot;bashir@test.com&quot;, &quot;0722345673&quot;, dob);<br>        accountRequest = TestDataProvider.createAccountRequest(&quot;Abdirahman&quot;, &quot;Abdi&quot;, &quot;1234567&quot;, &quot;bashir@test.com&quot;, &quot;0722345673&quot;, dob);<br><br>    }<br><br><br>    // add account details endpoint<br>    @DisplayName(&quot;verify add account details should return success&quot;)<br>    @Order(1)<br>    @Test<br>    public void addAccountDetails() throws Exception {<br>       LocalDate START_OF_1994 = LocalDate.of(1994, 1, 1);<br>       LocalDate END_OF_1994 = LocalDate.of(1994, 12, 31);<br><br>        // Arrange<br>        String validJson = objectMapper.writeValueAsString(accountRequest);<br>        when(accountService.addAccount(any(AccountRequest.class))).thenReturn(ResponseEntity.ok(account));<br><br>        // Act<br>        MvcResult result = mockMvc.perform(post(&quot;/api/v1/accounts&quot;)<br>                        .contentType(MediaType.APPLICATION_JSON)<br>                        .content(validJson))<br>                .andExpect(status().isOk())<br>                .andExpect(jsonPath(&quot;$.accountNumber&quot;).value(account.getAccountNumber()))<br>                .andExpect(jsonPath(&quot;$.email&quot;).value(account.getEmail()))<br>                .andDo(print())<br>                .andReturn();<br><br>        // Assert<br>        String jsonResponse = result.getResponse().getContentAsString();<br>        DocumentContext jsonContext = JsonPath.parse(jsonResponse);<br>        LocalDate dob = LocalDate.parse(jsonContext.read(&quot;$.dateOfBirth&quot;, String.class));<br><br>        assertTrue(!dob.isBefore(START_OF_1994) &amp;&amp; !dob.isAfter(END_OF_1994),<br>                &quot;Date of birth is not within the year 1994&quot;);<br><br>        verify(accountService, times(1)).addAccount(any(AccountRequest.class));<br>    }<br><br><br>    //add account with empty required fields<br><br>@DisplayName(&quot;verify add account details with empty fields should throw an errors&quot;)<br>@Order(2)<br>@Test<br>    public void  addAccountDetailsWithBlankRequiredFields() throws Exception {<br>    //arrange<br>        AccountRequest emptyFieldsRequest = AccountRequest.<br>                builder().<br>                firstName(&quot;&quot;).<br>                middleName(&quot;Abdirahman&quot;).<br>                lastName(null).<br>                accountNumber(&quot;&quot;).<br>                mobileNumber(&quot;0700916533&quot;).<br>                email(&quot;bashir.abdi@test.com&quot;).<br>                dateOfBirth(null).<br>                build();<br><br>    String JsonFields = objectMapper.writeValueAsString(emptyFieldsRequest);<br><br><br>    //acct and assert<br><br>    mockMvc.perform(post(&quot;/api/v1/accounts&quot;).<br>            contentType(MediaType.APPLICATION_JSON).<br>            content(JsonFields)<br>    ).<br>            andExpect(status().isBadRequest()).<br>            andExpect(jsonPath(&quot;$.message&quot;).value(&quot;Validation Errors&quot;)).<br>            andExpect(jsonPath(&quot;$.errors&quot;).isArray()).<br>            andExpect(jsonPath(&quot;$.errors&quot;,hasSize(4))).<br>            andExpect(jsonPath(&quot;$.errors&quot;,containsInAnyOrder(<br>                    &quot;accountRequest : First name is required.&quot;,<br>                    &quot;accountRequest : Last name is required.&quot;,<br>                    &quot;accountRequest : Date of birth is required&quot;,<br>                    &quot;accountRequest : Account number is required.&quot;<br>            ))).<br>            andDo(print());<br><br><br>    //verify no interaction<br><br>    verify(accountService,never()).addAccount(any(AccountRequest.class));<br><br><br><br>    }<br>// email format validation<br><br>    @DisplayName(&quot;verify add account details with invalid email format should throw an errors&quot;)<br>    @Order(3)<br>    @Test<br>    public void  addAccountDetailsWithInvalidEmailFormat() throws Exception {<br><br>        //Arrange<br>        // Create a date that is definitely in the past, e.g., 30 years ago from now<br>        LocalDate localDateOfBirth = LocalDate.now().minusYears(30);<br>        // Convert LocalDate to Date<br>        Date dateOfBirth = Date.from(localDateOfBirth.atStartOfDay(ZoneId.systemDefault()).toInstant());<br><br>      AccountRequest invalidEmailFormat =AccountRequest.<br>              builder().<br>              firstName(&quot;Abdi&quot;).<br>              middleName(&quot;Abdirahman&quot;).<br>              lastName(&quot;Abdi&quot;).<br>              accountNumber(&quot;345678&quot;).<br>              mobileNumber(&quot;0700916533&quot;).<br>              email(&quot;bashir.abdi@test&quot;).<br>              dateOfBirth(dateOfBirth).<br>              build();<br><br>      String  jsonFormat = objectMapper.writeValueAsString(invalidEmailFormat);<br><br><br>      //act and assert<br><br>        mockMvc.perform(post(&quot;/api/v1/accounts&quot;)<br>                .contentType(MediaType.APPLICATION_JSON).<br>                content(jsonFormat)<br>        ).<br>                andExpect(status().isBadRequest()).<br>                andExpect(jsonPath(&quot;$.message&quot;).value(&quot;Validation Errors&quot;)).<br>                andExpect(jsonPath(&quot;$.errors&quot;).isArray()).<br>                andExpect(jsonPath(&quot;$.errors&quot;,hasSize(1))).<br>                andExpect(jsonPath(&quot;$.errors[0]&quot;).value( &quot;accountRequest : Email format is invalid. Please provide a valid email address.&quot;)).<br>                andDo(print());<br><br>        //verify no interaction<br>        verify(accountService, never()).addAccount(any(AccountRequest.class));<br>    }<br><br><br>    //Invalid mobile number size and date of birth format<br><br>    @DisplayName(&quot;verify add account details with invalid phone number format and Future DOB should throw an errors&quot;)<br>    @Order(4)<br>    @Test<br>    public void  addAccountDetailsWithInvalidMobileNumberSizeAndDateOfBirthFormat() throws Exception {<br><br>        //arrange<br>        LocalDate localDateOfBirth = LocalDate.now().plusYears(2);<br>        // Convert LocalDate to Date<br>        Date dateOfBirth = Date.from(localDateOfBirth.atStartOfDay(ZoneId.systemDefault()).toInstant());<br>        AccountRequest invalidRequest = AccountRequest.<br>                builder().<br>                firstName(&quot;Abdi&quot;).<br>                middleName(&quot;Abdirahman&quot;).<br>                lastName(&quot;Abdi&quot;).<br>                accountNumber(&quot;345678&quot;).<br>                mobileNumber(&quot;070091653&quot;).<br>                email(&quot;bashir.abdi@test.com&quot;).<br>                dateOfBirth(dateOfBirth).<br>                build();<br><br>        String invalidObject = objectMapper.writeValueAsString(invalidRequest);<br><br><br>        //act and assert<br><br>        mockMvc.perform(post(&quot;/api/v1/accounts&quot;)<br>                .contentType(MediaType.APPLICATION_JSON)<br>                .content(invalidObject)<br>        )<br>                .andExpect(status().isBadRequest())<br>                .andExpect(jsonPath(&quot;$.message&quot;).value(&quot;Validation Errors&quot;))<br>                .andExpect(jsonPath(&quot;$.errors&quot;).isArray())<br>                .andExpect(jsonPath(&quot;$.errors&quot;,hasSize(2)))<br>                .andExpect(jsonPath(&quot;$.errors&quot;,containsInAnyOrder(<br>                        &quot;accountRequest : Mobile number must be between 10 and 15 digits.&quot;,<br>                        &quot;accountRequest : Date of birth must be in the past&quot;<br>                )))<br>                .andDo(print());<br><br><br>        //verify no interaction between controller and service layer<br><br><br>        verify(accountService, never()).addAccount(any(AccountRequest.class));<br>    }<br><br><br><br>// add account details with duplicate account number<br><br>    @DisplayName(&quot;Verify add account with duplicate account number should return error&quot;)<br>    @Test<br>    @Order(5)<br>    public void shouldReturnErrorWhenAddingAccountWithDuplicateNumber() throws Exception {<br>        //arrange<br>        LocalDate localDateOfBirth = LocalDate.now().minusYears(22);<br>        // Convert LocalDate to Date<br>        Date dateOfBirth = Date.from(localDateOfBirth.atStartOfDay(ZoneId.systemDefault()).toInstant());<br>        AccountRequest duplicateRequest =AccountRequest.<br>                builder().<br>                firstName(&quot;Asho&quot;).<br>                middleName(&quot;Ahmed&quot;).<br>                lastName(&quot;Abdi&quot;).<br>                accountNumber(&quot;1234567&quot;).<br>                mobileNumber(&quot;0700815432&quot;).<br>                dateOfBirth(dateOfBirth).<br>                email(&quot;asho.ahmed1@gmail.com&quot;).<br>                build();<br><br>        String jsonRequest = objectMapper.writeValueAsString( duplicateRequest);<br>        String validRequest =objectMapper.writeValueAsString(accountRequest);<br><br>        //act and assert for first valid request<br><br>        when(accountService.addAccount(any(AccountRequest.class))).thenReturn(ResponseEntity.ok(account));<br>        mockMvc.perform(post(&quot;/api/v1/accounts&quot;).<br>                contentType(MediaType.APPLICATION_JSON).<br>                content(validRequest)<br>        ).<br>                andExpect(status().isOk()).<br>                andDo(print());<br><br>        //verify the interaction for the first valid request<br>        verify(accountService).addAccount(any(AccountRequest.class));<br><br>      //simulate a duplicate entry scenario<br>        when(accountService.addAccount(any(AccountRequest.class))).<br>                thenThrow(new DataIntegrityViolationException(&quot;An entity with the same identifier (e.g., account number) already exists.&quot;));<br><br>        //act and assert<br>        mockMvc.perform(post(&quot;/api/v1/accounts&quot;)<br>                .contentType(MediaType.APPLICATION_JSON)<br>                .content(jsonRequest)<br>        ).<br>                andExpect(status().isBadRequest()).<br>                andExpect(jsonPath(&quot;$.message&quot;).value(&quot;Data Integrity Error&quot;)).<br>                andExpect(jsonPath(&quot;$.errors&quot;).isArray()).<br>                andExpect(jsonPath(&quot;$.errors&quot;,hasSize(1))).<br>                andExpect(jsonPath(&quot;$.errors[0]&quot;).value(&quot;Operation cannot be performed due to a data integrity violation.&quot;)).<br>                andDo(print());<br><br><br>        //verify no interaction<br>        verify(accountService,times(2)).addAccount(any(AccountRequest.class));<br><br>    }<br><br>//add account details with duplicate email<br><br><br>    @DisplayName(&quot;Verify add account with duplicate email should return error&quot;)<br>    @Test<br>    @Order(6)<br>    public void shouldReturnErrorWhenAddingAccountWithDuplicateEmail() throws Exception {<br>        //arrange<br>        LocalDate localDateOfBirth = LocalDate.now().minusYears(22);<br>        // Convert LocalDate to Date<br>        Date dateOfBirth = Date.from(localDateOfBirth.atStartOfDay(ZoneId.systemDefault()).toInstant());<br>        AccountRequest duplicateEmailRequest =AccountRequest.<br>                builder().<br>                firstName(&quot;Asho&quot;).<br>                middleName(&quot;Ahmed&quot;).<br>                lastName(&quot;Abdi&quot;).<br>                accountNumber(&quot;12345679&quot;).<br>                mobileNumber(&quot;0700815432&quot;).<br>                dateOfBirth(dateOfBirth).<br>                email(&quot;bashir@test.com&quot;).<br>                build();<br><br>        String jsonRequest = objectMapper.writeValueAsString( duplicateEmailRequest);<br>        String validRequest =objectMapper.writeValueAsString(accountRequest);<br><br>        //Act and Assert for first valid request<br><br>        when(accountService.addAccount(any(AccountRequest.class))).thenReturn(ResponseEntity.ok(account));<br>        mockMvc.perform(post(&quot;/api/v1/accounts&quot;).<br>                        contentType(MediaType.APPLICATION_JSON).<br>                        content(validRequest)<br>                ).<br>                andExpect(status().isOk()).<br>                andDo(print());<br><br>        //verify the interaction for the first valid request<br>        verify(accountService).addAccount(any(AccountRequest.class));<br><br>        //simulate a duplicate entry scenario<br>        when(accountService.addAccount(any(AccountRequest.class))).<br>                thenThrow(new DataIntegrityViolationException(&quot;An entity with the same identifier (e.g., account number) already exists.&quot;));<br><br>        //act and assert<br>        mockMvc.perform(post(&quot;/api/v1/accounts&quot;)<br>                        .contentType(MediaType.APPLICATION_JSON)<br>                        .content(jsonRequest)<br>                ).<br>                andExpect(status().isBadRequest()).<br>                andExpect(jsonPath(&quot;$.message&quot;).value(&quot;Data Integrity Error&quot;)).<br>                andExpect(jsonPath(&quot;$.errors&quot;).isArray()).<br>                andExpect(jsonPath(&quot;$.errors&quot;,hasSize(1))).<br>                andExpect(jsonPath(&quot;$.errors[0]&quot;).value(&quot;Operation cannot be performed due to a data integrity violation.&quot;)).<br>                andDo(print());<br><br><br>        //verify no interaction<br>        verify(accountService,times(2)).addAccount(any(AccountRequest.class));<br>    }<br><br><br>    //verify get all account details should return success<br><br>    @DisplayName(&quot;verify get all acount details should return success&quot;)<br>    @Test<br>    @Order(7)<br>    public void getAllAccountDetailsShouldReturnSuccess() throws Exception {<br>        //Arrange<br>       List&lt;AccountResponse&gt;accountResponse = TestDataProvider.createTestAccountResponses();<br>       ResponseEntity&lt;List&lt;AccountResponse&gt;&gt;expectedResponse =new ResponseEntity&lt;&gt;(accountResponse,HttpStatus.OK);<br><br>        when(accountService.getAllAccounts()).thenReturn(expectedResponse);<br><br>        mockMvc.perform(get(&quot;/api/v1/accounts&quot;)<br>                .contentType(MediaType.APPLICATION_JSON))<br>                .andExpect(status().isOk()).<br>                andExpect(jsonPath(&quot;$&quot;,hasSize(accountResponse.size()))).<br>                andExpect(jsonPath(&quot;$[0].email&quot;).value(accountResponse.get(0).getEmail()))<br>                .andDo(print());<br><br><br>        //verify there is one interaction<br><br>        verify(accountService,times(1)).getAllAccounts();<br><br>    }<br><br>    @DisplayName(&quot;Verify get account with Valid Account Number and Email should return success&quot;)<br>    @Test<br>    @Order(8)<br>    public void getAccountDetailsWithValidAccountNumberAndEmailReturnSuccess() throws Exception {<br>        // Arrange<br><br>        String accountNumber = TestDataProvider.createTestAccountResponses().get(0).getAccountNumber();<br>        String email = TestDataProvider.createTestAccountResponses().get(0).getEmail();<br>        when(accountService.findAccountDetails(accountNumber, email)).<br>                thenReturn(Optional.of(TestDataProvider.createTestAccountResponses().get(0)));<br>        //Act and Assert<br>    mockMvc.perform(get(&quot;/api/v1/accounts/details&quot;)<br>            .contentType(MediaType.APPLICATION_JSON)<br>            .param(&quot;accountNumber&quot;,accountNumber)<br>            .param(&quot;email&quot;,email)<br>    ).<br>            andExpect(status().isOk()).<br>            andExpect(header().string(&quot;Content-Type&quot;, &quot;application/json&quot;)).<br>            andExpect(jsonPath(&quot;$.accountNumber&quot;).value(accountNumber)).<br>            andExpect(jsonPath(&quot;$.email&quot;).value(email)).<br>            andDo(print());<br><br><br>    //verify the interaction<br>    verify(accountService,times(1)).findAccountDetails(accountNumber,email);<br><br><br><br>}<br>    @DisplayName(&quot;Verify get account with InValid Account Number and Email should throw an error&quot;)<br>    @Test<br>    @Order(9)<br>    public void getAccountDetailsWithInValidAccountNumberAndEmailReturnSuccess() throws Exception {<br>        //Arrange<br>        String accountNumber =&quot;45678901&quot;;<br>        String email = &quot;cbc.test@gmail.com&quot;;<br>        String message = &quot;account number : &quot; + accountNumber + &quot; and email : &quot; + email + &quot;not found. Please try with a valid account number and email.&quot;;<br>        when(accountService.findAccountDetails(accountNumber,email)).<br>                thenThrow(new UserNotFoundException(message));<br><br>        //Act and Assert<br>        mockMvc.perform(get(&quot;/api/v1/accounts/details&quot;).<br>                contentType(MediaType.APPLICATION_JSON).<br>                param(&quot;accountNumber&quot;,accountNumber).<br>                param(&quot;email&quot;,email)<br>                ).<br>                andExpect(status().isNotFound()).<br>                andExpect(jsonPath(&quot;$.message&quot;).value(&quot;Resource Not Found&quot;)).<br>                andExpect(jsonPath(&quot;$.errors[0]&quot;).value(message)).<br>                andDo(print());<br><br><br>        //verify the service interaction<br>        verify(accountService,times(1)).findAccountDetails(accountNumber,email);<br><br><br>    }<br>    @DisplayName(&quot;Test: Updating account details with valid account number and email should succeed&quot;)<br>    @Test<br>    @Order(10)<br>    public void shouldUpdateAccountDetailsSuccessfullyWithValidData() throws Exception {<br>        // Arrange<br>        AccountResponse testAccount = TestDataProvider.createTestAccountResponses().get(0);<br>        String accountNumber = testAccount.getAccountNumber();<br>        String email = testAccount.getEmail();<br><br>        AccountRequest accountRequest = AccountRequest.builder()<br>                .firstName(&quot;Mohamed&quot;)<br>                .middleName(&quot;Ahmed&quot;)<br>                .lastName(&quot;Kahim&quot;)<br>                .mobileNumber(testAccount.getMobileNumber())<br>                .accountNumber(accountNumber)<br>                .email(email)<br>                .dateOfBirth(testAccount.getDateOfBirth())<br>                .build();<br><br>        AccountResponse expectedUpdatedAccount = AccountResponse.builder()<br>                .firstName(accountRequest.getFirstName())<br>                .middleName(accountRequest.getMiddleName())<br>                .lastName(accountRequest.getLastName())<br>                .mobileNumber(testAccount.getMobileNumber())<br>                .accountNumber(accountNumber)<br>                .email(email)<br>                .dateOfBirth(testAccount.getDateOfBirth())<br>                .build();<br><br>        String jsonRequest = objectMapper.writeValueAsString(accountRequest);<br><br>        when(accountService.UpdateAccountDetails(any(AccountRequest.class), eq(accountNumber), eq(email)))<br>                .thenReturn(new ResponseEntity&lt;&gt;(expectedUpdatedAccount, HttpStatus.OK));<br><br>        // Act and Assert<br>        mockMvc.perform(put(&quot;/api/v1/accounts/{accountNumber}/{email}&quot;, accountNumber, email)<br>                        .contentType(MediaType.APPLICATION_JSON)<br>                        .content(jsonRequest))<br>                .andExpect(status().isOk()).<br>                andExpect(jsonPath(&quot;$.email&quot;).value(email))<br>                .andExpect(jsonPath(&quot;$.accountNumber&quot;).value(accountNumber))<br>                .andExpect(jsonPath(&quot;$.firstName&quot;).value(expectedUpdatedAccount.getFirstName()))<br>                .andDo(print());<br><br>        // Verify<br>        verify(accountService, times(1))<br>                .UpdateAccountDetails(any(AccountRequest.class), eq(accountNumber), eq(email));<br>    }<br><br>    //update account details with either wrong account number or email<br><br>    @DisplayName(&quot;Test: Updating account details with Invalid account number or email should throw an error&quot;)<br>    @Test<br>    @Order(11)<br>    public void shouldUpdateAccountDetailsUnSuccessfulWithInValidData() throws Exception {<br>        // Arrange<br>        AccountResponse testAccount =TestDataProvider.createTestAccountResponses().get(0);<br>        //wrong email<br>        String email =&quot;omar.bashir@test.com&quot;;<br>        //correct accountNumber<br>        String accountNumber = testAccount.getAccountNumber();<br>        //account request --&gt; what goes to the body of the request<br>        AccountRequest testRequest = AccountRequest.<br>                builder().<br>                firstName(&quot;Shukri&quot;).<br>                middleName(&quot;Kahin&quot;).<br>                lastName(testAccount.getLastName()).<br>                email(email).<br>                accountNumber(accountNumber).<br>                mobileNumber(testAccount.getMobileNumber()) .<br>                dateOfBirth(testAccount.getDateOfBirth()).<br>                build();<br><br>        //ExpectedResponse returns the api<br><br>        AccountResponse expectedResponse = AccountResponse.<br>                builder().<br>                firstName(testRequest.getFirstName()).<br>                middleName(testRequest.getMiddleName()).<br>                lastName(testRequest.getLastName()).<br>                email(testRequest.getEmail()).<br>                accountNumber(testRequest.getAccountNumber()).<br>                mobileNumber(testRequest.getMobileNumber()).<br>                dateOfBirth(testRequest.getDateOfBirth()).<br>                build();<br>        String formattedJson = objectMapper.writeValueAsString(testRequest);<br>        String message = &quot;account number : &quot; + accountNumber + &quot; and email : &quot; + email + &quot;not found. Please try with a valid account number and email.&quot;;<br>        //Act and Assert<br>        when(accountService.UpdateAccountDetails<br>                (any(AccountRequest.class),eq(accountNumber),eq(email))).<br>                thenThrow(new UserNotFoundException(message))  ;<br>        mockMvc.perform(put(&quot;/api/v1/accounts/{accountNumber}/{email}&quot;,accountNumber,email).<br>                contentType(MediaType.APPLICATION_JSON)<br>                .content(formattedJson)).<br>                andExpect(status().isNotFound()).<br>                andExpect(jsonPath(&quot;$.message&quot;).value(&quot;Resource Not Found&quot;))<br>                .andExpect(jsonPath(&quot;$.errors[0]&quot;).value(message)).<br>                andDo(print());<br><br><br>        //verify there is on interaction<br>        verify(accountService,times(1)).<br>                UpdateAccountDetails(any(AccountRequest.class),eq(accountNumber),eq(email));<br><br><br>    }<br><br>    @DisplayName(&quot;Test: Updating Partially account details with valid should return success&quot;)<br>    @Test<br>    @Order(12)<br>    public void shouldPartialUpdateAccountDetailsSuccessfullyWithValidData() throws Exception {<br>        // Arrange<br><br>        //arrange<br>        LocalDate localDateOfBirth = LocalDate.now().minusYears(26);<br>        // Convert LocalDate to Date<br>        Date dateOfBirth = Date.from(localDateOfBirth.atStartOfDay(ZoneId.systemDefault()).toInstant());<br>        AccountResponse originalAccountResponse = TestDataProvider.createTestAccountResponses().get(0);<br>        String accountNumber = originalAccountResponse.getAccountNumber();<br>        String email = originalAccountResponse.getEmail();<br><br>        //What goes to the body of the request---&gt; fields to be updated<br>        AccountPartialUpdateRequest partialUpdateRequest =<br>                AccountPartialUpdateRequest.<br>                        builder().<br>                        mobileNumber(&quot;0733816522&quot;).<br>                        dateOfBirth(dateOfBirth).<br>                        build();<br><br>        //Expected Response<br>        AccountResponse expectedResponse = AccountResponse.<br>                builder().<br>                firstName(originalAccountResponse.getFirstName()).<br>                middleName(originalAccountResponse.getMiddleName()).<br>                lastName(originalAccountResponse.getLastName()).<br>                accountNumber(originalAccountResponse.getAccountNumber()).<br>                email(originalAccountResponse.getEmail()).<br>                mobileNumber(partialUpdateRequest.getMobileNumber()).<br>                dateOfBirth(partialUpdateRequest.getDateOfBirth()).<br>                build();<br><br>        when(accountService.<br>                updateAccountDetailsPartially(any(AccountPartialUpdateRequest.class),eq(accountNumber),eq(email))).<br>                thenReturn(new ResponseEntity&lt;&gt;(expectedResponse,HttpStatus.OK));<br><br>        String jsonBody = objectMapper.writeValueAsString(partialUpdateRequest);<br><br>        //Act and Assert<br><br>        mockMvc.perform(patch<br>                (&quot;/api/v1/accounts/partial/{accountNumber}/{email}&quot;,accountNumber,email)<br>                .contentType(MediaType.APPLICATION_JSON)<br>                .content(jsonBody)).<br>                andExpect(status().isOk()).<br>                andExpect(jsonPath(&quot;$.dateOfBirth&quot;).value(dateOfBirth)).<br>                andExpect(jsonPath(&quot;$.mobileNumber&quot;).value(expectedResponse.getMobileNumber())).<br>                andDo(print());<br><br><br>        //verify<br><br>        verify(accountService,times(1)).<br>                updateAccountDetailsPartially(any(AccountPartialUpdateRequest.class),eq(accountNumber),eq(email));<br><br>    }<br><br>    @DisplayName(&quot;Test: Updating Partially account details with invalid accountNumber and email should Throw an error!&quot;)<br>    @Test<br>    @Order(13)<br>    public void shouldPartialUpdateAccountDetailsUnSuccessfulWithInValidEmailOrAccountNumber() throws Exception {<br>        // Arrange<br><br>        //arrange<br>        LocalDate localDateOfBirth = LocalDate.now().minusYears(26);<br>        // Convert LocalDate to Date<br>        Date dateOfBirth = Date.from(localDateOfBirth.atStartOfDay(ZoneId.systemDefault()).toInstant());<br><br>        AccountResponse originalAccountResponse = TestDataProvider.createTestAccountResponses().get(0);<br>        //wrong accountNumber<br>        String accountNumber =&quot;2907666&quot;;<br>        String email = originalAccountResponse.getEmail();<br><br>        //What goes to the body of the request---&gt; fields to be updated<br>        AccountPartialUpdateRequest partialUpdateRequest =<br>                AccountPartialUpdateRequest.<br>                        builder().<br>                        mobileNumber(&quot;0733816522&quot;).<br>                        dateOfBirth(dateOfBirth).<br>                        build();<br><br>        //Expected Response<br>        AccountResponse expectedResponse = AccountResponse.<br>                builder().<br>                firstName(originalAccountResponse.getFirstName()).<br>                middleName(originalAccountResponse.getMiddleName()).<br>                lastName(originalAccountResponse.getLastName()).<br>                accountNumber(originalAccountResponse.getAccountNumber()).<br>                email(originalAccountResponse.getEmail()).<br>                mobileNumber(partialUpdateRequest.getMobileNumber()).<br>                dateOfBirth(partialUpdateRequest.getDateOfBirth()).<br>                build();<br>        String message = &quot;account number : &quot; + accountNumber + &quot; and email : &quot; + email + &quot;not found. Please try with a valid account number and email.&quot;;<br><br>        when(accountService.<br>                updateAccountDetailsPartially(any(AccountPartialUpdateRequest.class),eq(accountNumber),eq(email))).<br>               thenThrow(new UserNotFoundException(message));<br><br>        String jsonBody = objectMapper.writeValueAsString(partialUpdateRequest);<br>       //Act and Assert<br><br>        mockMvc.perform(patch<br>                        (&quot;/api/v1/accounts/partial/{accountNumber}/{email}&quot;,accountNumber,email)<br>                        .contentType(MediaType.APPLICATION_JSON)<br>                        .content(jsonBody)<br>        ).<br>                andExpect(status().isNotFound()).<br>                andExpect(jsonPath(&quot;$.message&quot;).value(&quot;Resource Not Found&quot;)).<br>                andExpect(jsonPath(&quot;$.errors[0]&quot;).value(message)).<br>                andDo(print());<br><br><br><br><br>        //verify<br><br>        verify(accountService,times(1)).<br>                updateAccountDetailsPartially(any(AccountPartialUpdateRequest.class),eq(accountNumber),eq(email));<br><br>    }<br><br><br>    //Delete account details with valid accountNumber and email<br><br>    @DisplayName(&quot;Test:verify delete account details with valid accountNumber and email should return success&quot;)<br>    @Order(14)<br>    @Test<br>    public void shouldDeleteAccountDetailsWithValidAccountNumberAndEmailReturnSuccessful() throws Exception {<br>        // Arrange: Setup a test account with valid account number and email<br>        AccountResponse testAccount  = TestDataProvider.createTestAccountResponses().get(0);<br>        String accountNumber = testAccount.getAccountNumber();<br>        String email  = testAccount.getEmail();<br><br>        when(accountService.deleteAccountDetails(accountNumber,email)).<br>                thenReturn(new ResponseEntity&lt;&gt;(HttpStatus.OK));<br><br>        //Act and Assert<br>        mockMvc.perform(<br>                delete(&quot;/api/v1/accounts/{accountNumber}/{email}&quot;,accountNumber,email)<br>                        .contentType(MediaType.APPLICATION_JSON)<br>        ).<br>                andExpect(status().isOk()).<br>                andDo(print());<br><br><br>       // Verify that the service method was called with the correct parameters<br>        verify(accountService,times(1)).deleteAccountDetails(eq(accountNumber), eq(email));<br>    }<br><br><br><br><br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZPUQHCCfb7-IpzOtHAaD0Q.png" /></figure><h3>Mockito Usage:</h3><ul><li><strong>Mocking Dependencies</strong>: @Mock annotation is used to create mock instances of the AccountService, isolating the controller from service layer dependencies.</li><li><strong>Dependency Injection</strong>: @InjectMocks annotation injects mock instances into the tested object, here the AccountController, ensuring that the controller uses the mocked AccountService during tests.</li><li><strong>Behavior Simulation</strong>: when(...).thenReturn(...) and when(...).thenThrow(...) methods simulate the AccountService behavior. These methods define how the mock should behave when specific conditions are met, such as returning a response entity or throwing an exception.</li></ul><h3>JUnit Usage:</h3><ul><li><strong>Test Structure</strong>: JUnit’s @Test annotation marks the test methods. @BeforeEach sets up common prerequisites for the tests, such as initializing the MockMvc object and test data.</li><li><strong>Execution Order</strong>: @TestMethodOrder(MethodOrderer.OrderAnnotation.class) and @Order annotations define the order in which tests should run, ensuring dependency between tests is managed correctly.</li><li><strong>Assertions</strong>: Assertions (assertTrue, assertEquals) are used to verify the outcomes of the tests, such as response status codes and content.</li></ul><h3>MockMvc:</h3><ul><li>Utilized for simulating HTTP requests (get, post, put, delete) to the controller and asserting the outcomes. It&#39;s initialized with MockMvcBuilders, incorporating the controller and exception handling setup.</li><li>andExpect methods coupled with matchers (status(), jsonPath()) validate the HTTP response status and content.</li></ul><p><strong>Exception Handling:</strong></p><ul><li>Custom exceptions like UserNotFoundException are tested to ensure the controller provides the correct response when exceptions are thrown by the service layer.</li></ul><p><strong>Data Handling:</strong></p><ul><li>ObjectMapper is used for serializing request objects to JSON and deserializing responses for assertions.</li><li>JSON Path and Hamcrest Matchers (jsonPath(), Matchers.containsInAnyOrder) are employed to assert specific details within the JSON response</li></ul><h3>Conclusion</h3><p>The AccountController provides a comprehensive set of endpoints for managing account information in a RESTful manner, following best practices in Spring Boot application development. Through clear documentation and adherence to REST principles, it ensures easy integration and interaction with client applications.</p><p>Enjoyed this? Smash that like button and follow me for more awesome content!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=342b5d096973" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>