<?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 Rasheed Shaik on Medium]]></title>
        <description><![CDATA[Stories by Rasheed Shaik on Medium]]></description>
        <link>https://medium.com/@rasheed99?source=rss-d6b8ec72e7f9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*W2PAjk5NS_w6oBuQ</url>
            <title>Stories by Rasheed Shaik on Medium</title>
            <link>https://medium.com/@rasheed99?source=rss-d6b8ec72e7f9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 11:59:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rasheed99/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[Kafka 101: Store Kafka Events in MinIO Using Kafka Connect]]></title>
            <link>https://medium.com/@rasheed99/store-kafka-events-in-minio-using-kafka-connect-e19b28bd2ffc?source=rss-d6b8ec72e7f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/e19b28bd2ffc</guid>
            <category><![CDATA[minio]]></category>
            <category><![CDATA[kafka-connect]]></category>
            <category><![CDATA[s3-storage-classes]]></category>
            <category><![CDATA[kafka-sink-connect]]></category>
            <category><![CDATA[kafka]]></category>
            <dc:creator><![CDATA[Rasheed Shaik]]></dc:creator>
            <pubDate>Tue, 19 Nov 2024 16:03:55 GMT</pubDate>
            <atom:updated>2024-11-19T16:09:19.293Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6PDK4cu9PmLKHQX3QFXDcw.png" /></figure><p>Kafka is a powerful event-streaming platform, and MinIO provides a high-performance, S3-compatible object storage solution. Storing Kafka events in MinIO allows you to archive event data for analytics, compliance, or other downstream use cases.</p><p>In this article, we’ll set up a Kafka connector to stream Kafka events into MinIO.</p><h3>Architecture Overview</h3><ol><li><strong>Kafka + Zookeeper</strong>: The backbone for event streaming.</li><li><strong>Kafka Connect</strong>: To bridge Kafka and MinIO.</li><li><strong>MinIO</strong>: An S3-compatible object storage system.</li><li><strong>S3 Sink Connector</strong>: To stream Kafka events into MinIO.</li></ol><blockquote>Step 1: Prepare a docker-compose.yml file</blockquote><p>We’ll create a Docker Compose file to spin up all necessary services.</p><pre>version: &#39;3.8&#39;<br>services:<br>  zookeeper:<br>    image: confluentinc/cp-zookeeper:latest<br>    environment:<br>      ZOOKEEPER_CLIENT_PORT: 2181<br>    ports:<br>      - &quot;2181:2181&quot;<br><br>  kafka:<br>    container_name: kafka<br>    image: confluentinc/cp-kafka:latest<br>    depends_on:<br>      - zookeeper<br>    environment:<br>      KAFKA_BROKER_ID: 1<br>      KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181<br>      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka:9092<br>      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT<br>      KAFKA_INTER_BROKER_LISTENER_NAME: PLAINTEXT  <br>      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1<br>    ports:<br>      - &quot;9092:9092&quot;<br><br>  kafka-connect:<br>    image: confluentinc/cp-kafka-connect:latest<br>    depends_on:<br>      - kafka<br>      - minio<br>    environment:<br>      CONNECT_BOOTSTRAP_SERVERS: kafka:9092<br>      CONNECT_REST_PORT: 8083<br>      CONNECT_GROUP_ID: &quot;connect-cluster&quot;<br>      CONNECT_REST_ADVERTISED_HOST_NAME: &quot;kafka-connect&quot;<br>      CONNECT_CONFIG_STORAGE_TOPIC: &quot;connect-configs&quot;<br>      CONNECT_OFFSET_STORAGE_TOPIC: &quot;connect-offsets&quot;<br>      CONNECT_STATUS_STORAGE_TOPIC: &quot;connect-status&quot;<br>      CONNECT_CONFIG_STORAGE_REPLICATION_FACTOR: 1<br>      CONNECT_OFFSET_STORAGE_REPLICATION_FACTOR: 1<br>      CONNECT_STATUS_STORAGE_REPLICATION_FACTOR: 1<br>      CONNECT_KEY_CONVERTER: &quot;org.apache.kafka.connect.storage.StringConverter&quot;<br>      CONNECT_VALUE_CONVERTER: &quot;org.apache.kafka.connect.json.JsonConverter&quot;<br>      CONNECT_INTERNAL_KEY_CONVERTER: &quot;org.apache.kafka.connect.storage.StringConverter&quot;<br>      CONNECT_INTERNAL_VALUE_CONVERTER: &quot;org.apache.kafka.connect.json.JsonConverter&quot;<br>      CONNECT_PLUGIN_PATH: &quot;/usr/share/java,/etc/kafka-connect/plugins&quot;<br>    ports:<br>      - &quot;8083:8083&quot;<br>    volumes:<br>      - ./plugins:/etc/kafka-connect/plugins<br><br>  minio:<br>    container_name: minio<br>    image: minio/minio:latest<br>    command: server /data --console-address &quot;:9001&quot;<br>    environment:<br>      MINIO_ROOT_USER: &quot;minio&quot;<br>      MINIO_ROOT_PASSWORD: &quot;minio123&quot;<br>      MINIO_DEFAULT_BUCKETS: &quot;my-bucket&quot;<br>    ports:<br>      - &quot;9000:9000&quot;<br>      - &quot;9001:9001&quot;<br>    healthcheck:<br>      test: [ &quot;CMD&quot;, &quot;curl&quot;, &quot;-f&quot;, &quot;http://localhost:9000/minio/health/live&quot; ]<br>      interval: 30s<br>      timeout: 20s<br>      retries: 3<br><br>  createbucket:<br>    image: minio/mc<br>    depends_on:<br>      minio:<br>        condition: service_healthy<br>    entrypoint: &gt;<br>      /bin/sh -c &quot;<br>      /usr/bin/mc alias set myminio http://minio:9000 minio minio123;<br>      /usr/bin/mc mb myminio/my-bucket;<br>      /usr/bin/mc policy set public myminio/my-bucket;<br>      exit 0;<br>      &quot;</pre><blockquote>Step 2: Add the S3 Sink Connector</blockquote><ul><li>Create setup-connector.sh bash script inside ./plugins folder</li></ul><pre>#!/bin/bash<br><br>CONNECTOR_URL=&quot;https://path-to-s3-sink-connector.jar&quot;<br>PLUGINS_DIR=&quot;./plugins&quot;<br><br>if [[ -d &quot;$PLUGINS_DIR&quot; ]]; then<br>  echo &quot;The plugins directory already exists. Skipping download.&quot;<br>else<br>  echo &quot;Creating plugins directory...&quot;<br>  mkdir -p &quot;$PLUGINS_DIR&quot;<br><br>  echo &quot;Downloading S3 Sink Connector...&quot;<br>  wget -q --show-progress -P &quot;$PLUGINS_DIR&quot; &quot;$CONNECTOR_URL&quot;<br><br>  if [[ $? -eq 0 ]]; then<br>    echo &quot;S3 Sink Connector downloaded successfully to $PLUGINS_DIR.&quot;<br>  else<br>    echo &quot;Failed to download the S3 Sink Connector. Please check the URL or your network connection.&quot;<br>    exit 1<br>  fi<br>fi</pre><ul><li>Make it executable and Run it</li></ul><pre>chmod +x setup-connector.sh &amp;&amp; ./setup-connector.sh</pre><blockquote>Step 3: Start the Services</blockquote><p>Run the Docker Compose setup:</p><pre>docker-compose up -d</pre><blockquote>Step 4: Configure the Connector</blockquote><ul><li>Create the minio-sink-connector.json configuration file:</li></ul><pre>{<br>  &quot;name&quot;: &quot;minio-sink-connector&quot;,<br>  &quot;config&quot;: {<br>    &quot;connector.class&quot;: &quot;io.confluent.connect.s3.S3SinkConnector&quot;,<br>    &quot;tasks.max&quot;: &quot;1&quot;,<br>    &quot;topics&quot;: &quot;test-topic&quot;,<br>    &quot;s3.bucket.name&quot;: &quot;my-bucket&quot;,<br>    &quot;s3.region&quot;: &quot;us-east-1&quot;,<br>    &quot;s3.part.size&quot;: &quot;5242880&quot;,<br>    &quot;store.url&quot;: &quot;http://minio:9000&quot;,<br>    &quot;s3.access.key.id&quot;: &quot;minio&quot;,<br>    &quot;s3.secret.access.key&quot;: &quot;minio123&quot;,<br>    &quot;s3.ssl.enabled&quot;: &quot;false&quot;,<br>    &quot;storage.class&quot;: &quot;io.confluent.connect.s3.storage.S3Storage&quot;,<br>    &quot;format.class&quot;: &quot;io.confluent.connect.s3.format.json.JsonFormat&quot;,<br>    &quot;partitioner.class&quot;: &quot;io.confluent.connect.storage.partitioner.DefaultPartitioner&quot;,<br>    &quot;flush.size&quot;: &quot;100&quot;,<br>    &quot;schema.compatibility&quot;: &quot;NONE&quot;<br>  }<br>}</pre><ul><li>Submit the configuration to Kafka Connect using its REST API</li></ul><pre>curl -X POST -H &quot;Content-Type: application/json&quot; --data @minio-sink-connector.json http://localhost:8083/connectors</pre><blockquote>Step 5: Test the Setup</blockquote><ul><li>Create the produce-event.sh configuration file:</li></ul><pre>#!/bin/bash<br><br>KAFKA_CONTAINER=&quot;kafka&quot;        <br>TOPIC_NAME=&quot;test-topic&quot;  <br>BROKER=&quot;localhost:9092&quot;   <br>EVENT=&#39;{&quot;data&quot;: &quot;sample event data&quot;}&#39; <br><br><br>echo $EVENT | docker exec -i $KAFKA_CONTAINER /usr/bin/kafka-console-producer \<br>  --broker-list $BROKER \<br>  --topic &quot;$TOPIC_NAME&quot;<br><br>echo &quot;Produced the event!&quot;</pre><ul><li>Make it executable and Run it</li></ul><pre>chmod +x produce-event.sh &amp;&amp; ./produce-event.sh</pre><ul><li>Verify the files in MinIO webUI by accessing http://localhost:9001</li></ul><h3>Conclusion</h3><p>In just a few steps, we’ve successfully set up Kafka Connect to stream event data into MinIO using the S3 Sink Connector. This integration allows you to leverage MinIO’s scalable object storage for Kafka event data.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e19b28bd2ffc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kafka 101: Introduction to Architecture]]></title>
            <link>https://medium.com/@rasheed99/kafka-101-introduction-to-architecture-e646b8f26baf?source=rss-d6b8ec72e7f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/e646b8f26baf</guid>
            <category><![CDATA[event-driven-architecture]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[kafka-architecture]]></category>
            <category><![CDATA[introduction]]></category>
            <dc:creator><![CDATA[Rasheed Shaik]]></dc:creator>
            <pubDate>Thu, 02 May 2024 17:03:27 GMT</pubDate>
            <atom:updated>2024-05-02T17:04:51.048Z</atom:updated>
            <content:encoded><![CDATA[<p>In today’s digital age, information moves at the speed of light. From social media updates to financial transactions, data is generated and consumed in massive quantities every second. But how does this data travel seamlessly from one place to another without getting lost or overwhelmed? The answer lies in Kafka.</p><blockquote>What is Kafka?</blockquote><p>Kafka is like a central hub for data, it’s a distributed streaming platform that allows you to publish, subscribe to, store, and process streams of records in real-time. In simpler terms, it’s a powerful tool that helps different parts of a system communicate with each other efficiently.</p><blockquote>Why do we need Kafka?</blockquote><p>Imagine you’re using messaging app. Kafka ensures smooth information flow, much like managing a busy messaging app where users can send and receive messages instantly. It coordinates message confirmations, updates, and notifications, preventing chaos and errors in real-time communication.</p><blockquote>Event-Driven Architecture</blockquote><p>Event-Driven Architecture (EDA) is a design pattern where components within a system communicate with each other by producing and consuming events. An event is a significant occurrence or change in state that has relevance to the system. Unlike traditional request-response models, where components interact synchronously, EDA allows for asynchronous communication, enabling decoupling and scalability of the system.</p><blockquote>Key Components of Kafka’s architecture</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gT8IQ7lOWcIzADR1mAcw1w.png" /><figcaption>Kafka Architecture</figcaption></figure><p>Let’s explore each component and its function with the messaging app example we have mentioned above.</p><blockquote><strong>Producer</strong></blockquote><p>This is where data is generated and sent to Kafka broker. Think of it as the starting point, like a factory producing goods.</p><p><strong>Example:</strong> Imagine you’re typing a message in the app and hit send. At that moment, your message becomes data that needs to be sent to other users. The part of the app responsible for sending your message out is the producer. It takes your message and sends it to the messaging platform which is kafka broker.</p><blockquote><strong>Broker</strong></blockquote><p>Brokers are the servers that form the core of Kafka. They store the incoming data and distribute it to the consumers. Picture them as warehouses storing goods before shipping them out.</p><p><strong>Example:</strong> Now, the message needs to be stored temporarily and then distributed to the intended recipients. The broker is like the central post office. It receives your message from the producer, holds onto it briefly, and then forwards it to the recipient(s). It ensures that the message is delivered reliably and efficiently.</p><blockquote><strong>Consumer</strong></blockquote><p>Consumers receive and process the data from Kafka. They’re like the end-users who receive the goods and make use of them.</p><p><strong>Example:</strong> On the receiving end, when someone else opens the app, they need to see the new message you sent. The part of the app that retrieves and displays the incoming messages is the consumer. It waits for new messages to arrive, retrieves them from the broker, and displays them to the user.</p><blockquote><strong>Topics</strong></blockquote><p>Topics are channels through which data is organized and distributed within Kafka. Each topic is divided into partitions, allowing for parallel processing. Think of topics as different categories of goods, and partitions as shelves within those categories.</p><p><strong>Example:</strong> In our messaging app example, the topic could be something like “ChatRoom.” It’s like a virtual room where all the messages are sent. When you send a message, it’s tagged with this topic so that the broker knows where to deliver it.</p><blockquote><strong>Partitions</strong></blockquote><p>Within each topic, data is further divided into partitions. Partitions allow for horizontal scalability and parallel processing of data. Each partition is stored on a separate broker, ensuring fault tolerance and high availability.</p><p><strong>Example:</strong> In the “ChatRoom” topic, messages are divided into partitions, acting as separate channels. For instance, one partition may handle messages from one friend group, while another manages messages from another group. This division will help to manage the workload distribution and ensures speedy message delivery.</p><blockquote><strong>Consumer Groups</strong></blockquote><p>Consumers are organized into groups to parallelize processing and scale out consumption. Each consumer group reads from one or more partitions of a topic. This enables efficient and load-balanced consumption of data.</p><p><strong>Example:</strong> In the app, users are grouped based on shared interests or conversations. Each group, acting as a consumer group, independently reads messages from partitions they’re interested in, ensuring everyone receives relevant messages without overwhelming the system.</p><blockquote><strong>Offsets</strong></blockquote><p>Offsets are like bookmarks that track the position of a consumer within a partition. They indicate the last record that a consumer has successfully processed. By keeping track of offsets, Kafka ensures that consumers can resume from where they left off in case of failures or restarts.</p><p><strong>Example:</strong> As messages are sent and received, the system keeps track of the position of each consumer within a partition. This position is called an offset. It helps ensure that each consumer knows which messages it has already received and which ones are new. For example, if you close the app and reopen it later, the system uses offsets to pick up where you left off, so you don’t miss any messages.</p><p>I trust that this article has helped you to grasp the key components of Kafka’s architecture.</p><p>Thank you for reading, and happy coding! 😊</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e646b8f26baf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Spring Security Architecture]]></title>
            <link>https://medium.com/@rasheed99/introduction-on-spring-security-architecture-eb5d7de75a4f?source=rss-d6b8ec72e7f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb5d7de75a4f</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[spring-security]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[spring]]></category>
            <dc:creator><![CDATA[Rasheed Shaik]]></dc:creator>
            <pubDate>Wed, 01 Nov 2023 08:12:56 GMT</pubDate>
            <atom:updated>2023-11-03T09:44:29.298Z</atom:updated>
            <content:encoded><![CDATA[<p>Spring Security acts as a vigilant guardian for your web applications. It oversees who can access your site, verifies user identities, and enforces rules to safeguard your data from unauthorized access.</p><p>In this blog, we’ll deep dive into the architecture of Spring Security, break down its essential parts, and see how they work together to keep your application safe and sound.</p><p>In Spring MVC, all incoming HTTP requests are channeled through a single servlet known as the DispatcherServlet. This servlet directs these requests to your controller classes, where you define the endpoints for your application. Spring Security steps in at this point by introducing filter classes before the HTTP requests reach the DispatcherServlet.</p><p>This means that every incoming request will pass through these filter classes one by one. This approach allows us to verify authentication and authorization states before the request reaches the DispatcherServlet and subsequently the controllers. In essence, this is the core function of Spring Security.</p><h3><strong>Spring Security Architecture</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kcfwR4V_9P8VjXz_xMgqZw.png" /><figcaption>Spring Security Architecture Diagram</figcaption></figure><h3><strong>Components of Architecture</strong></h3><blockquote><strong>Security Filter Chain</strong></blockquote><p>The Security Filter Chain is the backbone of Spring Security. It’s a series of filters that processes incoming HTTP requests and communicates with the Authentication Manager for the validation of requests.</p><p>These filters work together to ensure that your web application is secure and responsible for tasks like authentication, authorization, session management and more. The order in which these filters are applied matters, as each one handles each with a specific aspect of security.</p><p><strong>List of default Filters in Security Filter Chain</strong></p><ul><li><strong>ChannelProcessingFilter</strong> — ensures protocol such as HTTP or HTTPS.</li><li><strong>SecurityContextPersistenceFilter</strong> — ensures the user’s authentication details persist during their session.</li><li><strong>UsernamePasswordAuthenticationFilter</strong> — checks the provided credentials and creates an Authentication Object if they are valid.</li><li><strong>ConcurrentSessionFilter</strong> — control how many sessions a user can have and handle scenarios where a user exceeds the session limit.</li><li><strong>LogoutFilter</strong> — intercepts logout requests and terminates the user’s session.</li><li><strong>RememberMeAuthenticationFilter</strong> — allow user to be remembered across sessions, even after logout.</li><li><strong>AnonymousAuthenticationFilter</strong> — responsible for creating an anonymous user who is not authenticated but has limited access to some parts of the application.</li><li><strong>SessionManagementFilter</strong> — handles invalidating sessions, session fixation protection, and other session-related tasks.</li><li><strong>ExceptionTranslationFilter</strong> — responsible for translating the exception into a unauthenticated response.</li><li><strong>FilterSecurityInterceptor</strong> — ensures the user have the necessary roles and permissions to access specific resources.</li></ul><p>You can read more about filters<a href="https://docs.spring.io/spring-security/site/docs/3.0.x/reference/security-filter-chain.html"> here</a>.</p><pre>@Bean<br>public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) {<br>    httpSecurity.authorizeHttpRequests(authorize -&gt;<br>          authorize.requestMatchers(&quot;/signup/&quot;).permitAll()<br>                   .requestMatchers(&quot;/users&quot;).authenticated()<br>    ).httpBasic(Customizer.withDefaults());<br><br>    return httpSecurity.build();<br>}</pre><ul><li><em>This code defines a custom </em><em>Security Filter Chain with specific security rules. It permits unrestricted access to the </em><em>“/signup/” URL while requiring authentication for the </em><em>“/users” URL. Additionally, it configures </em><em>HTTP Basic Authentication as the authentication method.</em></li></ul><blockquote><strong>Authentication Manager</strong></blockquote><p>The Authentication Manager is the central component that verifies user identities. It coordinates the authentication process and delegates the actual authentication to Authentication Providers.</p><p>In more complex systems, you might have multiple Authentication Managers. Each manager can be associated with a specific set of Authentication Providers, allowing you to handle different types of authentication for different parts of your application.</p><blockquote><strong>Authentication Providers</strong></blockquote><p>The Authentication Providers are the workers of the Authentication Manager. They are responsible for actually performing the authentication.</p><p>Spring Security supports various types of Authentication Providers</p><ul><li><strong>DaoAuthenticationProvider — </strong>uses a UserDetailsService to retrieve user details from database and compare credentials.</li><li><strong>LdapAuthenticationProvider </strong>— used for authenticating against LDAP servers.</li><li><strong>JwtAuthenticationProvider </strong>— used for validating JWT tokens of the user.</li><li><strong>Custom Authentication Providers </strong>— handle authentication using specific logic or external systems.</li></ul><pre>@Bean<br>public DaoAuthenticationProvider daoAuthenticationProvider() {<br>    DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();<br>    daoAuthenticationProvider.setUserDetailsService(userDetailsService());<br>    daoAuthenticationProvider.setPasswordEncoder(passwordEncoder());<br>    return daoAuthenticationProvider;<br>}</pre><ul><li><em>In this snippet, a custom </em><em>DaoAuthenticationProvider is defined, configured with a </em><em>UserDetailsService and a </em><em>PasswordEncoder.</em></li></ul><blockquote><strong>UserDetailsService</strong></blockquote><p>The UserDetailsService is an interface which retrieves user details during the authentication process. It is often used in conjunction with Authentication Providers to obtain user details from the database for authentication.</p><pre>public class UserDetailsServiceImpl implements UserDetailsService {<br>    @Autowired<br>    public UserRepository userRepository;<br>    <br>    @Override<br>    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {<br>        Optional&lt;User&gt; user = userRepository.findById(username);<br>        if (user.isEmpty()) {<br>            throw new UsernameNotFoundException(&quot;user not found with this username&quot;);<br>        }<br><br>        return new UserDetailsImpl(user.get());<br>    }<br>}</pre><ul><li><em>The </em><em>UserDetailsServiceImpl class is implemented as a custom </em><em>UserDetailsService, and it overrides the </em><em>loadUserByUsername method to retrieve user details from a database via a </em><em>UserRepository.</em></li></ul><pre>@Bean<br>public UserDetailsService userDetailsService() {<br>    return new UserDetailsServiceImpl();<br>}</pre><ul><li><em>In the above code, we are defining </em><em>UserDetailsServiceImpl as custom </em><em>UserDetailsService .</em></li></ul><blockquote><strong>Password Encoder</strong></blockquote><p>The Password Encoder is used to hash and verify passwords securely as storing and comparing passwords is crucial for user authentication.</p><ul><li><strong>BCryptPasswordEncoder</strong> — this is widely recommended choice for securely hashing passwords in Spring Security. It handles the generation of random salts for each password.</li><li><strong>NoOpPasswordEncoder — </strong>this encoder does not perform any hashing or encoding of passwords and stores passwords in plain text which makes them highly vulnerable.</li><li><strong>StandardPasswordEncoder</strong> — this encoder uses one-way hashing algorithm which is less secure and it is not recommended.</li><li><strong>MessageDigestPasswordEncoder</strong> — this encoder uses a specified message digest algorithm (e.g., SHA-256) to hash passwords. While it’s more secure than plain text, it’s not as strong as BCrypt and is considered less secure in modern applications.</li><li><strong>SCryptPasswordEncoder</strong> — SCrypt is another secure password hashing algorithm, similar to BCrypt. It’s designed to be memory-intensive, making it resistant to certain types of attacks. SCryptPasswordEncoder is a good choice for secure password hashing.</li></ul><pre>@Bean<br>public PasswordEncoder passwordEncoder() {<br>    return new BCryptPasswordEncoder();<br>}</pre><ul><li><em>In the above code, a </em><em>BCryptPasswordEncoder is defined as the custom </em><em>PasswordEncoder .</em></li></ul><blockquote><strong>SecurityContextHolder and Principal</strong></blockquote><p>The SecurityContextHolder class manages the user’s security context throughout the request-response lifecycle. It stores information about the currently authenticated user such as roles, and other security-related data.</p><p>Once the user is successfully authenticated, Spring Security creates an Authentication Object within the security context managed by SecurityContextHolder.</p><p>The Principal represents the current user’s username, authorities, and other user-specific data.</p><pre>Authentication authentication = SecurityContextHolder.getContext().getAuthentication();<br>String username = authentication.getName();</pre><ul><li><em>The above code snippet is an example of how to retrieve the current user’s username from the </em><em>Principal .</em></li></ul><blockquote><strong>Request &amp; Response lifecycle</strong></blockquote><p>Now, let us combine all the components we have learned so far and understand the whole flow of the architecture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bXZoyANJiP9aqxSqtFbo_A.png" /></figure><ol><li>The request is intercepted by the Security Filter Chain. The Security Filter Chain consists of a series of filters, each with a specific security-related task.</li><li>If the user is not yet authenticated (i.e., not logged in), Spring Security’s authentication filters will trigger the Authentication Manager. If the credentials match, the Authentication Manager generates an Authentication Object indicating a successful authentication.</li><li>The Authentication Manager uses the configured Authentication Providers to verify the user’s credentials.</li><li>Authentication Providers will use the PasswordEncoder to store and compare passwords.</li><li>Authentication Providers may use the UserDetailsService to fetch user details. The user’s credentials are compared to the stored or provided credentials.</li><li>UserDetailsService will fetch the data from the database.</li><li>The status of the authentication process will be sent to the user as a success or unauthorized response.</li><li>This Authentication object is stored within the security context managed by SecurityContextHolder. The security context now represents the authenticated user.</li></ol><blockquote><strong>Conclusion</strong></blockquote><p>I trust that this blog has helped you grasp the key components, including the Security Filter Chain, Authentication Manager, Authentication Providers, UserDetailsService, Password Encoder, SecurityContextHolder, and Principal.</p><p>If you’d like to explore a simple Spring Security application, you can find one in this <a href="https://github.com/shaikrasheed99/springboot-security-basics">GitHub repository</a>.</p><p>Thank you for reading, and happy coding! 😊</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb5d7de75a4f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Write Benchmark Tests in Go]]></title>
            <link>https://medium.com/@rasheed99/how-to-write-benchmark-tests-in-go-86592d8cb789?source=rss-d6b8ec72e7f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/86592d8cb789</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[benchmark-testing]]></category>
            <category><![CDATA[tdd]]></category>
            <dc:creator><![CDATA[Rasheed Shaik]]></dc:creator>
            <pubDate>Fri, 30 Dec 2022 12:43:52 GMT</pubDate>
            <atom:updated>2022-12-30T12:44:25.560Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JaxkIA1vVwsHvXM-EcUgRw.png" /></figure><p>In this article, we are going to discuss how to write benchmark tests in Go.</p><p>This is one of the articles of the <a href="https://medium.com/@rasheed99/list/testing-in-go-dae544fc95a8">Testing in Go</a> series, please find some time to read the remaining articles as well.</p><p><strong>What is benchmark testing?</strong></p><p>Benchmark tests will measure the performance of a function or program. Also used to examine the runtime and the memory usage of a program by running multiple times.</p><p>In this article, we will create a simple project called factorial, where we will find the factorial of a number using the Iterative and Recursive approaches, and also test their performance through benchmark tests.</p><p><strong>Project creation:</strong></p><p>Open your terminal, go to your destination folder and run the below commands</p><ul><li><em>mkdir factorial — to create a project folder.</em></li><li><em>cd factorial — to go inside the greeting folder.</em></li><li><em>go mod init factorial</em><strong><em> —</em></strong><em> to create a Go project.</em></li><li><em>Above command will create a </em><em>go.mod file in the </em><em>factorial directory, that will have the metadata of third-party packages we use for our project.</em></li><li><em>If you are using VSCode also use </em><em>code . to open the IDE.</em></li></ul><p>Finally, we have set up our project. Now let’s start writing code!!!</p><p>As per TDD practices, let’s write the test case first and then code next.</p><p>To create a benchmark test, we need to follow the below rules</p><ul><li><em>The benchmark function needs to be inside a </em><em>*_test file.</em></li><li><em>The name of the function must start with a </em><em>Benchmark word.</em></li><li><em>The benchmark function must accept </em><em>*testing.B as the parameter.</em></li><li><em>The benchmark function must run the code for </em><em>b.N times.</em></li></ul><p>So, let’s quickly go and create a factorial_test.go test file inside the factorial folder. Make sure your test file should end with _test.go and put the test file in the same package as the one being tested.</p><p>We will create a test case to find the factorial of a given number using an iterative approach.</p><p>So, let’s try to write a test case where we will be providing a number to the factorialUsingIteration function and check whether it is returning the expected output.</p><p>Add the below test function to the factorial_test.go file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a9494eb93a5fa37e831492fa2d88b60/href">https://medium.com/media/4a9494eb93a5fa37e831492fa2d88b60/href</a></iframe><ul><li><em>As you have seen in the above code, we have followed every rule for creating benchmark tests.</em></li><li><em>Benchmark function would take </em><em>t *testing.B as a parameter where </em><em>B is a type passed to functions to manage benchmark timing and to specify the </em><em>b.N iterations to run.</em></li><li><em>b.N would be adjusted until the benchmark function lasts long enough to be timed reliably.</em></li></ul><p>Now, let’s try to run the test file.</p><p>To run a benchmark test, we can use the go test command with -bench flag by giving =. as an input for the flag.</p><pre>go test -bench=.</pre><p>So, open your terminal and run the above command. Ohh no, we got an error!!!</p><p>Congratulations, on our first error which generally indicates that we are going on the correct track. Now let’s try to look at the error about what it’s saying.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e6e8d00f398b5dab950c846a3766e843/href">https://medium.com/media/e6e8d00f398b5dab950c846a3766e843/href</a></iframe><p>This is a compile-time error and says that the test case is using the factorialUsingIteration function, which is not even defined yet. So, let’s try to define it.</p><p>Create a factorial.go to the same directory where factorial_test.go resides in and add the below code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9599232c7632d6b5c5ff17fbb67ec8f6/href">https://medium.com/media/9599232c7632d6b5c5ff17fbb67ec8f6/href</a></iframe><ul><li><em>func factorialUsingIteration(number int) int {} — here we are defining the function which would take the number as a parameter and return the factorial of that number using an iterative approach.</em></li></ul><p>Now, let’s try to run the test file again using the go test -bench=. command in the terminal.</p><p>What did you see in your terminal? Is it showing as PASS? Hurrah, our test case is finally passing!!!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/64657c0c88d50f9c1c756b613ce588d6/href">https://medium.com/media/64657c0c88d50f9c1c756b613ce588d6/href</a></iframe><ul><li><em>The output tells that the loop ran 417181020 times at a speed of 2.798 ns per loop.</em></li></ul><p>Finally, we have successfully completed our first test case. With this same knowledge and energy, let’s try to write one more test case.</p><p>This time, we will create a test case to find the factorial of a given number using a recursion approach.</p><p>So, add the below test function in the factorial_test.go file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1afb1056a60f0126014758fce149aed2/href">https://medium.com/media/1afb1056a60f0126014758fce149aed2/href</a></iframe><p>Now, let’s try to run the test file using the go test -bench=. command in the terminal.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/590b7f5625dde68057996964566f118f/href">https://medium.com/media/590b7f5625dde68057996964566f118f/href</a></iframe><p>We have got one more compilation error which says that the test case is using the factorialUsingRecursion function, which is not even defined yet. Let’s try to define it.</p><p>So, add the below test function in the factorial.go file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/249cf055794b22029f28a2b7a187bf30/href">https://medium.com/media/249cf055794b22029f28a2b7a187bf30/href</a></iframe><p>Now, let’s try to run the test file again using the go test -bench=. command in the terminal.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/84d11e361c9469053313d1671533fb76/href">https://medium.com/media/84d11e361c9469053313d1671533fb76/href</a></iframe><ul><li><em>Here we can compare both the approaches by the test outputs.</em></li><li><em>BenchmarkFactorialUsingIteration is taking 2.798 ns of time per loop.</em></li><li><em>BenchmarkFactorialUsingRecursion is taking 5.900 ns of time per loop.</em></li></ul><p>Our test case is finally passing but why are seeing both test cases running at the same time? Because we are told to run the whole file through the go test -bench=. command.</p><ul><li><em>go test -bench=. — used to run all the benchmark functions.</em></li><li><em>go test -bench=&lt;name of the function&gt; — used to run only selective benchmark function.</em></li></ul><p>Now, let’s try to run the BenchmarkFactorialUsingRecursion function using the go test -bench=BenchmarkFactorialUsingRecursion command in the terminal.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e33babe049ac29bd846d0f028d960837/href">https://medium.com/media/e33babe049ac29bd846d0f028d960837/href</a></iframe><p>Finally, we have successfully completed both the test cases. Congratulations!!!</p><p>This is all about How to write Benchmark tests in Go.</p><p>This is one of the articles of the <a href="https://medium.com/@rasheed99/list/testing-in-go-dae544fc95a8">Testing in Go</a> series, please find some time to read the remaining articles as well.</p><p>Hope you have understood this article and please try to write Benchmark tests in your projects as well.</p><p>As always, you can have a look at the complete code on <a href="https://github.com/shaikrasheed99/go-benchmark-tests-factorial">Git Repository</a>.</p><p>Thanks for reading, happy coding!!!</p><p>Feel free to connect with me on <a href="http://www.linkedin.com/in/shaikrasheed3011">LinkedIn</a>!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=86592d8cb789" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Write Subtests in Go]]></title>
            <link>https://medium.com/@rasheed99/how-to-write-subtests-in-go-7cd9c066579d?source=rss-d6b8ec72e7f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/7cd9c066579d</guid>
            <category><![CDATA[tdd]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[test-sub]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Rasheed Shaik]]></dc:creator>
            <pubDate>Sat, 17 Dec 2022 09:52:36 GMT</pubDate>
            <atom:updated>2022-12-17T10:35:18.578Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iOxiU0BQ9l0o-KzZ8JTY8A.png" /></figure><p>This article is a continuation of <a href="https://medium.com/@rasheed99/how-to-write-table-driven-tests-in-go-8e96ef048cca">Table-driven tests</a>, please make sure you have completed reading it before going further.</p><p><strong>Problem statement:</strong></p><p>Before diving into understanding the problem, let us look at the test code of greeting_table_driven_test.go from the <a href="https://medium.com/@rasheed99/how-to-write-table-driven-tests-in-go-8e96ef048cca">previous</a> article because we are going to use the same example in this article as well.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8dce384fa67617e74a690dc93ea1c188/href">https://medium.com/media/8dce384fa67617e74a690dc93ea1c188/href</a></iframe><p>In the above code, we have written table-driven test cases to test the Greet()<strong> </strong>function. It is usually a best practice to write test cases in a table-driven pattern, but as we discussed at the end of the <a href="https://medium.com/@rasheed99/how-to-write-table-driven-tests-in-go-8e96ef048cca">previous</a> article we cannot run selective test cases from table-driven tests as all the test cases were wrapped inside the slice of the struct type.</p><p>To tackle this problem, in 2016 Marcel van Lohuizen proposed the Subtests concept and included it in the Go (1.7) version. Please refer to this <a href="https://github.com/golang/proposal/blob/master/design/12166-subtests.md">proposal</a> to understand it clearly.</p><p>In this article, we are going to discuss how to write Subtests in Go and also discuss the way to run the selective test cases.</p><p><strong>What is Sub testing?</strong></p><blockquote>Sub-testing is a process of splitting our test functions into granular subfunctions.</blockquote><p><strong>Benefits of using Subtest?</strong></p><ul><li><em>We can group similar test functions to reduce the cognitive load.</em></li><li><em>We can give useful names to tests for better handling of errors and control over them.</em></li><li><em>We can have the ability to run Subtests parallelly and have more maintainable code.</em></li></ul><p><strong>How do we write subtests in Go?</strong></p><p>We can do it with the Run method of T type from the testing package that allows for the creation of subtests. It takes two arguments, one is the name of the subtest and another is subtest function. Technically, Run runs the function in a separate goroutine and blocks until it returns success or failure.</p><p>Enough of the theory, now let’s create a greeting_sub_test.go file and add the below code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ed0b30547132488916ab45c430e860eb/href">https://medium.com/media/ed0b30547132488916ab45c430e860eb/href</a></iframe><ul><li><strong><em>TestGreetWithSubTests()</em></strong><em> — since both the test cases are using </em><em>Greet() function, we have changed to simple name</em></li><li><strong><em>main *testing.T</em></strong><em> — named it as </em><em>main instead of </em><em>t just to understand clearly while comparing with subtests.</em></li><li><strong><em>main.Run()</em></strong><em> — defining the subtest by passing the name and subtest function to wrap the whole test case.</em></li><li><em>After that test logic remains the same as we discussed in the </em><a href="https://medium.com/@rasheed99/how-to-write-table-driven-tests-in-go-8e96ef048cca"><em>previous</em></a><em> article which includes defining expected output as a variable and calling the </em><em>Greet() function by passing name as an input and finally asserting to check for their equality.</em></li></ul><p>If you run the test file with the verbose flag using the go test -v command in the terminal. It will show the results of both unit tests, table-driven tests and subtests.</p><p>But we want to run only the subtests, for that we can use the go test -run by passing the name of the test function like below.</p><pre>go test -v -run TestGreetWithSubTests</pre><ul><li><em>Since our subtests were written inside one function, we are passing </em><strong><em>TestGreetWithSubTests</em></strong><em> to our </em><em>-run flag to run only selective functions.</em></li><li><em>In the above command, we are running only the selective function, not the selective test case.</em></li></ul><p>Did the test cases pass? Yes, you have finally learned about the Subtests topic as well. Congratulations!!!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/21f6608f92233dc80f0e421b893094ac/href">https://medium.com/media/21f6608f92233dc80f0e421b893094ac/href</a></iframe><p><strong>How do we run a selective test case?</strong></p><p>If you notice in the above terminal output, we are running both subtests at once using the go test -v -run TestGreetWithSubTests command. But how can we run the selective subtest?</p><p>We have to modify the input value to the -run flag. So, append the name of the test case to the name of the test function by including / in between. Use the below command to run specific subtests.</p><pre>go test -v -run TestGreetWithSubTests/ShouldBeAbleToGreetAsHelloWithName</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c133f9d0d08930f113964e7676031b70/href">https://medium.com/media/c133f9d0d08930f113964e7676031b70/href</a></iframe><p>This is all about How to Write Subtests in Go.</p><p>This is one of the articles of the <a href="https://medium.com/@rasheed99/list/testing-in-go-dae544fc95a8">Testing in Go</a> series, please find some time to read the remaining articles as well.</p><p>Hope you have understood this article and please try to write subtests in your go projects as well.</p><p>As always, you can have a look at the complete code on <a href="https://github.com/shaikrasheed99/go-testing-greet">Git Repository</a>.</p><p>Thanks for reading, happy coding!!!</p><p>Feel free to connect with me on <a href="http://www.linkedin.com/in/shaikrasheed3011">LinkedIn</a>!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7cd9c066579d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Write Table-driven Tests in Go]]></title>
            <link>https://medium.com/@rasheed99/how-to-write-table-driven-tests-in-go-8e96ef048cca?source=rss-d6b8ec72e7f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e96ef048cca</guid>
            <category><![CDATA[tdd]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[table-driven-testing]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Rasheed Shaik]]></dc:creator>
            <pubDate>Sat, 17 Dec 2022 06:15:32 GMT</pubDate>
            <atom:updated>2022-12-17T10:25:25.260Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jaBeQ57E9Q4xJuOokzGCGw.png" /></figure><p>This article is a continuation of <a href="https://medium.com/@rasheed99/how-to-write-unit-tests-in-go-a0492e18aff2">Unit Testing in Go</a>, please make sure you have completed reading it before going further.</p><p><strong>Problem statement:</strong></p><p>Before diving into understanding the problem, let us look at the test code of greeting_unit_test.go from the <a href="https://medium.com/@rasheed99/how-to-write-unit-tests-in-go-a0492e18aff2">previous</a> article because we are going to use the same example in this article as well.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/afccac3ef99ff8de4561b29b1977c21b/href">https://medium.com/media/afccac3ef99ff8de4561b29b1977c21b/href</a></iframe><p>In the above code, we have tested the Greet()<strong> </strong>function with two test cases. For each test case, we have created a separate function.</p><p>If we follow this pattern, we need to have a new function for a new test case even though we need to run the same Greet() function with different inputs, so basically the more test cases we add the more functions need to be created and the more code duplication will be formed which includes calling the same function, same assertion block will be added to the test file. It is not best practice for the real-world codebases.</p><p>In this article, we are going to discuss how to write Table-driven tests in Go.</p><p><strong>What is Table-driven testing?</strong></p><blockquote>Table-driven testing is a process of extracting patterns in test cases to eliminate test functions.</blockquote><p>Table-driven tests are the best-suited solution to avoid above mentioned code duplication where all the arguments and expectations of the test case would be wrapped inside a struct type.</p><p>So, whenever we need to test a new test case, we simply need to add an entry in the slice of the struct and the simple for loop would take care of running it. Table-driven tests are just an example of the DRY principle.</p><p><strong>Benefits of table-driven tests</strong></p><ul><li><em>We can reduce the repetitive code.</em></li><li><em>We can add test cases effortlessly without separate functions.</em></li><li><em>We can have more transparency regarding the quality of test inputs.</em></li></ul><p><strong>How do we write table-driven tests in Go?</strong></p><p>Typically every test case will have a description, input, and expected output values. So, we will create a simple struct type by including attributes like below.</p><pre>type TestCase struct {<br>    description string<br>    name        string<br>    want        string<br>}</pre><p>The above struct will be useful for a single test case but if we have multiple test cases, we simply have to create a []TestCase{} (slice of that struct) and add entity test case data to that slice.</p><p>After that, with the help of a loop, we have to traverse the whole slice and gather the output for the assertions between expected and actual outputs.</p><p>Enough of the theory, now let’s create a greeting_table_driven_test.go file and add the below code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8dce384fa67617e74a690dc93ea1c188/href">https://medium.com/media/8dce384fa67617e74a690dc93ea1c188/href</a></iframe><ul><li><em>As we discussed earlier, we have taken a </em><em>testCase struct to hold single test case data and the slice of that struct to hold multiple </em><em>testCases data.</em></li><li><em>Since we have only two test cases we have taken two entities in the slice.</em></li><li><em>We have used a for loop to traverse the slice and gather the actual outputs for assertions.</em></li><li><em>Inside the for loop, you might have observed the </em><em>t.Run() function, which is nothing but a method of </em><em>T type used to create subtests. To know more about Subsets, please refer to this </em><a href="https://medium.com/@rasheed99/how-to-write-subtests-in-go-7cd9c066579d"><em>article</em></a><em>.</em></li></ul><p>If you run the test file with the verbose flag using the go test -v command in the terminal. It will show the results of both unit tests and table-driven tests.</p><p>But we want to run only the table-driven tests, for that we can use the go test -run by passing the name of the test function like below.</p><pre>go test -v -run TestGreetWithTableDrivenTests</pre><ul><li><em>Since our table-driven tests were written inside one function, we are passing </em><em>TestGreetWithTableDrivenTests to our </em><em>-run flag to run only selective functions.</em></li><li><em>In the above command, we are running only the selective function, not the selective test case.</em></li></ul><p>Did the test cases pass? Yes, you have finally learned about the Table-driven tests topic as well. Congratulations!!!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f35ade14360a292dbf0c24cd8c6fc740/href">https://medium.com/media/f35ade14360a292dbf0c24cd8c6fc740/href</a></iframe><p><strong>How do we run a selective test case?</strong></p><p>If you notice in the above terminal output, we are running all the test cases with the go test -v -run TestGreetWithTableDrivenTests command. But what if we want to run only a selective test case?</p><p>Unfortunately, we cannot run selective test cases in table-driven tests as all the test cases were wrapped inside the slice.</p><p>But we can use Subsets type of testing to run selective test cases. I have clearly explained it, please try to find some time to have a look at this <a href="https://medium.com/@rasheed99/how-to-write-subtests-in-go-7cd9c066579d">article</a>.</p><p>This is all about How to Write Table-driven tests in Go.</p><p>This is one of the articles of the <a href="https://medium.com/@rasheed99/list/testing-in-go-dae544fc95a8">Testing in Go</a> series, please find some time to read the remaining articles as well.</p><p>Hope you have understood this article and please try to write table-driven tests in your go projects as well.</p><p>As always, you can have a look at the complete code on <a href="https://github.com/shaikrasheed99/go-testing-greet">Git Repository</a>.</p><p>Thanks for reading, happy coding!!!</p><p>Feel free to connect with me on <a href="http://www.linkedin.com/in/shaikrasheed3011">LinkedIn</a>!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e96ef048cca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Write Unit Tests in Go]]></title>
            <link>https://medium.com/@rasheed99/how-to-write-unit-tests-in-go-a0492e18aff2?source=rss-d6b8ec72e7f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/a0492e18aff2</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[tdd]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[unit-testing]]></category>
            <dc:creator><![CDATA[Rasheed Shaik]]></dc:creator>
            <pubDate>Fri, 16 Dec 2022 17:00:56 GMT</pubDate>
            <atom:updated>2023-03-13T09:44:01.474Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U9QHOej1vgugfG_sL6eKRA.png" /></figure><p>In this article, we are going to discuss how to write unit tests in Golang. Go doesn’t need much introduction like other languages because it was built to build secure, scalable systems. Refer to this <a href="https://go.dev/doc/">blog</a> to know more about Go.</p><p><strong>What is Unit Testing?</strong></p><blockquote>Software is made of small unit components called functions, objects, structs, methods, modules, etc. To validate each unit and check its correctness, we use Unit Testing which is the first level of the Test Pyramid.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wZLcujP8828FDOZ-zTFWzQ.png" /><figcaption>Test Pyramid</figcaption></figure><p><strong>How can we write unit tests in Go?</strong></p><blockquote>Go provides a built-in package called testing to test the go codes using the go test command. Go doesn’t let us use any third-party libraries for basic testing.</blockquote><p>In this article, we will create a simple project called Greeting, which will greet Hello with a name. We will also write some unit test cases to test the greeting functionality.</p><p><strong>Prerequisites:</strong></p><ul><li><em>Good understanding of Go.</em></li><li><em>Download Go on your machine from </em><a href="https://go.dev/dl/"><em>here</em></a><em>.</em></li><li><em>An IDE to write and run the code.</em></li></ul><p><strong>Project creation:</strong></p><p>Open your terminal, go to your destination folder and run the below commands.</p><ul><li><em>mkdir greeting</em><strong><em> — </em></strong><em>to create a project folder.</em></li><li><em>cd greeting</em><strong><em> — </em></strong><em>to go inside the greeting folder.</em></li><li><em>go mod init greeting — to create a Go project.</em></li><li><em>Above command will create a </em><em>go.mod file in the </em><em>greeting directory, that will have the metadata of third party packages we use for our project.</em></li><li><em>If you are using VSCode, use </em><em>code . to open the IDE.</em></li></ul><p>Finally, we have set up our project. Now let’s start writing code!!!</p><p>As per the thumb rule of TDD (If you are hearing TDD for the first time, please refer to this <a href="https://www.guru99.com/test-driven-development.html">blog</a> to know more about it), we need to add a test case first and then code next.</p><p>So, let’s quickly go and create a greeting_unit_test.go test file inside the greeting folder. Make sure your test file should end with _test.go because go will recognise only _test.go files as test files and put the test file in the same package as the one being tested.</p><p>So far so good, we got to know the convention that needs to be followed to create a testing file. But what are we going to test?</p><p>As we discussed earlier, we are going to create a greeting functionality that will greet us Hello with whatever name we provide to it.</p><p>So, let’s try to write a test case where we will be providing a name to the Greet() function and check whether it is returning the expected output. Add the below test function to the greeting_unit_test.go file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5b32c191e8f587c617314cc2417940ef/href">https://medium.com/media/5b32c191e8f587c617314cc2417940ef/href</a></iframe><ul><li><em>package greeting — defining greeting as a package that is generally used for grouping featured files into units.</em></li><li><em>import “testing” — importing built-in testing package to test easily.</em></li><li><em>func TestShouldBeAbleToGreetAsHelloWithName(t *testing.T) {} — here we are defining a function for our test case by following the </em><em>TestXxx convention because it helps Go to recognise them as test functions. </em><em>Xxx (refers to the name of the test case, please make sure you use the first letter of the name as capital).</em></li><li><em>Test function would take </em><em>t *testing.T as a parameter where </em><em>T is a struct that can be used to manage test state and support formatted test logs.</em></li><li><em>name:= “Ironman” — here we are taking the name inside a variable.</em></li><li><em>want:= “Hello, Ironman!!” — here we are taking the expected hello message inside a want variable.</em></li><li><em>got:= Greet(name) — here we are calling our </em><em>Greet() function by passing the name and storing the result message inside the got variable.</em></li><li><em>In the final </em><em>if block, we are checking whether our expected want and the actual got are equal, if they are equal it means our test case is working fine, but if they are not equal we are telling that our test case failed with some error through </em><em>t.Error() function. We can use third-party packages to shorten this block by using </em><em>assertions, we are going to discuss assertions in the upcoming refactoring section of this article.</em></li><li><em>t.Error() is actually a combination of </em><em>t.Fail (marks the function as failed) and </em><em>t.Log (used to print custom messages as logs).</em></li></ul><p>Finally, we have clearly understood the code. Now, let’s try to run the test file.</p><p>To run test files, we use the go test command which basically searches for the files which end with _test.go in the current directory. If you want to know more about it, use the go help test command.</p><p>So, open your terminal and run the go test command. Ohh no, we got an error!!!</p><p>Congratulations, on our first error which generally indicates that we are going on the correct track. Now let’s try to look at the error about what it’s saying.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5121f3b7954fcaefe4666c01ff371bfe/href">https://medium.com/media/5121f3b7954fcaefe4666c01ff371bfe/href</a></iframe><p>This is a compile-time error and says that the test case is using the Greet() function, which is not even defined yet. So, let’s try to define it.</p><p>Create a greeting.go in the same directory where greeting_unit_test.go resides in and add the below code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5bdb67037956115e531c09a88da409fd/href">https://medium.com/media/5bdb67037956115e531c09a88da409fd/href</a></iframe><ul><li><em>package greeting — defining greeting as a package, if you observe we have defined the same package for the test file too.</em></li><li><em>func Greet(name string) string {} — here we are defining the function which would take the name as a parameter and return the hello message.</em></li></ul><p>Now, let’s try to run the test file again using the go test command in the terminal.</p><p>What did you see in your terminal? Is it showing as PASS? Hurrah, our test case is finally passing!!!</p><p>We can use the verbose flag to the go test -v command to see more details about the output in the terminal.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/164655a768da38b3db129c264a234e8f/href">https://medium.com/media/164655a768da38b3db129c264a234e8f/href</a></iframe><p>Finally, we have successfully completed our first test case. With this same knowledge and energy, let’s try to write one more test case.</p><p>As per TDD rules, let’s write the test case first and then code next.</p><p>So, what is our test case this time?</p><p>We are going to test our greeting functionality by passing an empty name, technically we will send an empty string to the Greet() function. In this scenario, our Greet() function should return a hello message with an anonymous as the default name. Let’s write the test case to check whether it is returning the expected output.</p><p>Add the below test function to the greeting_unit_test.go file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0834700470abb8070b7a4bcd6a3817e9/href">https://medium.com/media/0834700470abb8070b7a4bcd6a3817e9/href</a></iframe><ul><li><em>Here we are storing an empty string inside the name variable, passing it to the </em><em>Greet() function, and expecting </em><em>“Hello, Anonymous!!”.</em></li></ul><p>Now, run the test file using the go test command in the terminal. We are seeing the below output, right?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b79408792eda2df081f0dd698d99b688/href">https://medium.com/media/b79408792eda2df081f0dd698d99b688/href</a></iframe><p>Are you able to understand anything from the above error message? No!!!</p><p>This is because the above error is not a compilation error to have a meaningful message from the Go. But that is an assertion error, where our expected want is not equal to actually got. So, how are we going to deal with this kind of situation? We could use third-party packages to give meaningful assertion errors or else we can have our custom messages. We will see how to use third-party packages in the refactoring section, but as of now let’s try to use custom messages.</p><p>To create custom assertion messages, we can make use of the t.Log() which internally resides inside t.Error(). So, modify the test function with the below line of code.</p><pre>t.Error(&quot;(&quot;, want, &quot;) is not equal to (&quot;, got, &quot;)&quot;)</pre><p>Now, run the test file using the go test command in the terminal. Now, are you able to understand the exact error message? Yes!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0b9147a13c268c464a260d9ddc15f42a/href">https://medium.com/media/0b9147a13c268c464a260d9ddc15f42a/href</a></iframe><p>It basically says that we are expecting “Hello, Anonymous!!” but the Greet() function is returning only “Hello, !!” which means we have to modify our greeting functionality.</p><p>So, modify Greet() with the below code in the greeting.go file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/66b0d7a80bed1bb930c0a58d8bac1b83/href">https://medium.com/media/66b0d7a80bed1bb930c0a58d8bac1b83/href</a></iframe><p>Now, run the test file with the verbose flag using the go test -v command in the terminal.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ff4a50590e14489c9e1fbd0433223a06/href">https://medium.com/media/ff4a50590e14489c9e1fbd0433223a06/href</a></iframe><p>Our test case is finally passing but why are we seeing both the test cases are running at the same time? Because we are told to run the whole file through the go test -v command.</p><p>Do we have any way to run only the specific test case? Yes, we can add the -run flag to our go test command.</p><p>Now, run the test file again with the run flag using the below command.</p><pre>go test -v -run TestShouldBeAbleToGreetAsHelloWithAnonymousName</pre><p>In the above command, the name of the test function is the regex that is an argument to the -run flag.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/df8f4d1d75211890b2c964c74f69914a/href">https://medium.com/media/df8f4d1d75211890b2c964c74f69914a/href</a></iframe><p>Finally, we have successfully completed both the test cases. Congratulations!!!</p><p>Now, let’s do some refactoring!</p><p>We have seen one issue in the if blocks of test functions right? We can refactor it with the third-party package called to <a href="https://pkg.go.dev/github.com/stretchr/testify">testify</a>.</p><p>To install this package in our project, use the go get github.com/stretchr/testify command in the terminal. It will create the required dependencies in go.mod file and some binaries in go.sum file.</p><p>Refactor the greeting_unit_test.go file with the below code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/afccac3ef99ff8de4561b29b1977c21b/href">https://medium.com/media/afccac3ef99ff8de4561b29b1977c21b/href</a></iframe><ul><li><em>As you can see in both test functions, we have reduced the length of code by erasing the if block with assertions of the testify package.</em></li></ul><p>Refactor the greeting.go file with the below code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d51300cd6827187d0e7cf33c90791175/href">https://medium.com/media/d51300cd6827187d0e7cf33c90791175/href</a></iframe><ul><li><em>Here we have declared a few variables for the hard-coded strings so that we can use them for later usage.</em></li></ul><p>I would highly recommend you use the below commands frequently.</p><ul><li><em>go test — run the test file.</em></li><li><em>go test -v — run the test file with verbose.</em></li><li><em>go test -run &lt;name of the function&gt; — run the specific test function.</em></li><li><em>go test -cover — run the test file with coverage of code.</em></li></ul><p>If you notice the greeting_unit_test.go file, we are having separate functions for each of the test cases that are actually putting some load on Go to run and also having code duplication.</p><p>To avoid these problems, we can use the below topics for refactoring our test file. I have clearly explained about them as well, please try to find some time to have a look.</p><ul><li><a href="https://medium.com/@rasheed99/how-to-write-table-driven-tests-in-go-8e96ef048cca">Table-driven tests</a></li><li><a href="https://medium.com/@rasheed99/how-to-write-subtests-in-go-7cd9c066579d">Subtests</a></li></ul><p>This is all about How to write Unit tests in Go.</p><p>This is one of the articles of the <a href="https://medium.com/@rasheed99/list/testing-in-go-dae544fc95a8">Testing in Go</a> series, please find some time to read the remaining articles as well.</p><p>Hope you have understood this article and please try to write unit tests in your go projects as well.</p><p>As always, you can have a look at the complete code on <a href="https://github.com/shaikrasheed99/go-testing-greet">Git Repository</a>.</p><p>Thanks for reading, happy coding!!!</p><p>Feel free to connect with me on <a href="http://www.linkedin.com/in/shaikrasheed3011">LinkedIn</a>!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a0492e18aff2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pagination and Sorting using Spring Boot with TDD — Part I]]></title>
            <link>https://medium.com/@rasheed99/pagination-and-sorting-using-spring-boot-with-tdd-part-i-c6533aa57a0c?source=rss-d6b8ec72e7f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/c6533aa57a0c</guid>
            <category><![CDATA[pagination]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[tdd]]></category>
            <category><![CDATA[rest-api]]></category>
            <dc:creator><![CDATA[Rasheed Shaik]]></dc:creator>
            <pubDate>Sun, 20 Nov 2022 15:05:29 GMT</pubDate>
            <atom:updated>2022-12-29T04:57:50.118Z</atom:updated>
            <content:encoded><![CDATA[<h3>Pagination and Sorting using Spring Boot with TDD — Part I</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2lzQnqC6TSz5FJ6qNvg-mA.png" /></figure><p>In this post, we are going to discuss how to create RESTful APIs with Pagination and Sorting using Spring Boot by following TDD.</p><p>When we are trying to create an API that has to fetch a whole lot of records from a database, it would generally take more time while querying from the database and also takes more load time while sending that data to the client. Clients will also end up in an infinite scrolling loop of that huge data.</p><p>To solve this problem, we have multiple solutions but in this post, we will be discussing Pagination, which is also one of the solutions.</p><p><strong>What is Pagination?</strong></p><blockquote>Pagination is the process of partitioning the data content into discrete pages.</blockquote><p><strong>What are the benefits of Pagination?</strong></p><blockquote>Pagination returns structured chunks of data so as to make users choose further content through backward and forward navigation links.</blockquote><blockquote>Pagination also reduces network traffic load time by sending shorter and smaller pages to the client.</blockquote><p><strong>What is Sorting and its benefits?</strong></p><blockquote>Like pagination, sorting is also one of the important features of an API. If you are sending data to the client, your client may want the data in ascending or descending order of a particular field. Then you have to sort the result data.</blockquote><p>Enough of theory, now let’s dive into building the project.</p><p><strong>Prerequisites of the project:</strong></p><ul><li>Java</li><li>Minimal understanding of Spring Boot, Spring MVC, and Rest APIs.</li><li>Little bit of experience on TDD in Spring Boot.</li></ul><p><strong>Tech stack:</strong></p><ul><li>JDK 11</li><li>Gradle</li><li>Spring Boot (2.7.5)</li><li>H2 database</li><li>JPA</li><li>Mockito</li></ul><p><strong>Our Goals for this post!</strong></p><p>We are going to build a simple spring boot application which consists of below four APIs.</p><ol><li>Get the list of Avengers data without pagination and sorting.</li><li>Get the list of Avengers data with pagination.</li><li>Get the list of Avengers data by sorting on a particular field.</li><li>Get the list of Avengers data with a combination of pagination and sorting.</li></ol><p><strong>Let’s start building the project!!!</strong></p><p><strong>Project Creation</strong></p><ul><li>To begin, go to <a href="https://start.spring.io/">https://start.spring.io/</a></li><li>Choose a Gradle project and add dependencies including Web, JPA, H2 (you can google to know more about them).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a2hTaqiwpelDB3f4WMujmQ.png" /></figure><ul><li>Click on the Generate ⌘ + ↩ button and it will download a zip file (pagination_and_sorting.zip)</li><li>You can unzip it, move that folder to your destination, and open it in your IDE. I’m using IntelliJ, so I would highly recommend you use IntelliJ as well.</li><li>Open IntelliJ IDE and go to build.gradle and please make sure the content inside it should be similar to the below code.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/69b737fec4ca2b7f98f3ef7f8c07a381/href">https://medium.com/media/69b737fec4ca2b7f98f3ef7f8c07a381/href</a></iframe><p><strong>Structure the project files</strong></p><p>Basically Spring follows the MVC model, so let’s try to structure our files in this fashion.</p><p>Client request follows these steps (Client -&gt; Controller Layer -&gt; Service Layer -&gt; Model Layer) and responds in reverse order.</p><ul><li><strong>Controller Layer</strong> (handles all kinds of HTTP requests from the client).</li><li><strong>Service Layer</strong> (consists of all kinds of Business logic needed for the application, I’m actually skipping this layer because we are simply fetching the data from the database and it doesn’t require much business logic. If you are very curious to implement, I would highly recommend you give it a try).</li><li><strong>Model Layer</strong> (manipulation of data will be done in this layer).</li></ul><p>So, please make sure you follow the picture below to structure your files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*fZwbyrG7QsMqVW5-QrUFXw.png" /><figcaption>Structure the project files</figcaption></figure><p><strong>Configure H2 database</strong></p><ul><li>Now, let’s try to configure our H2 database.</li><li>Open application.properties through path src/main/resources/application.properties</li><li>And add the below code inside your application.properties file.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/55177ad151425ea21f390697649a9e65/href">https://medium.com/media/55177ad151425ea21f390697649a9e65/href</a></iframe><p>Finally, we are done with structuring the files and configuration of the H2 database.</p><p><strong>Now, let’s try to start coding…!</strong></p><p><strong>API — 1. List of Avengers data without pagination and sorting</strong></p><p>We will be trying to build our first API.</p><p>Before writing code for it, let’s try to think about the output of our API. We simply need to return the list of avengers right? To return a list of anything, we can use java’s built-in <strong>List</strong> data structure. But what about the avengers, java doesn’t have any built-in class or package to create avengers.</p><p>To do that, we need a class to represent the data of avengers. For that, we are going to create a class called <strong>Avenger</strong> and declare it as <strong>Entity</strong> (refer to this <a href="https://www.baeldung.com/jpa-entities">blog</a> to know more about Entity).</p><p>Now, create an Avenger.java file inside src/main/java/com/pagination_and_sorting/model/ folder and add the below code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d9e6287a768c02f80d1237b2ec2ec417/href">https://medium.com/media/d9e6287a768c02f80d1237b2ec2ec417/href</a></iframe><p>If you feel there are so many new words or annotations in the above code, please use google to know more about them.</p><p>So far, we have an Avenger class to create avengers but how are we going to manage them in the H2 database?</p><p>To do that Spring Data JPA provides an interface called <strong>JpaRepository</strong>, which provides a bunch of built-in methods to do crud operations on the database.</p><p>Our API needs to fetch the list of avengers from the database, for that we will be using the built-in <strong>findAll()</strong> method of JpaRepository.</p><p>As we discussed in the beginning, we are going to do this project in a TDD fashion. So, we will be writing the test case first, then the actual logic next.</p><p>So, let’s try to code our first test case to test the <strong>save()</strong> method of JpaRepository..!</p><p>Formally, we aren’t required to test built-in methods of JpaRepository, but I’m just writing one sample test case to give you an idea of how to write test cases for JpaRepository especially when you have written custom queries on the database.</p><p>So, create an AvengerRepositoryTest.java file inside src/test/java/com/pagination_and_sorting/model/ folder and add the below code.</p><pre>package com.pagination_and_sorting.model;<br><br>import org.junit.jupiter.api.Test;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;<br>import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;<br><br>import static org.junit.jupiter.api.Assertions.assertEquals;<br><br>@DataJpaTest<br>@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)<br>public class AvengerRepositoryTest {<br>    @Autowired<br>    private AvengerRepository avengerRepository;<br><br>    @Test<br>    void shouldBeAbleToSaveAvengerDetails() {<br>        Avenger ironman = new Avenger(&quot;Ironman&quot;, &quot;Iron Man&quot;, 2008);<br>        Avenger savedIronman = avengerRepository.save(ironman);<br><br>        assertEquals(savedIronman.getId(), ironman.getId());<br>        assertEquals(savedIronman.getName(), ironman.getName());<br>        assertEquals(savedIronman.getIntroducedInMovie(), ironman.getIntroducedInMovie());<br>    }<br>}</pre><p>Now, try to run this test case using the IntelliJ shortcut (Ctrl + Shift + R).</p><p>Is it passing? No, we are seeing the error message.</p><pre>error: cannot find symbol<br>    private AvengerRepository avengerRepository;<br>            ^<br>  symbol:   class AvengerRepository<br>  location: class AvengerRepositoryTest</pre><p>Because our test case is communicating with <strong>AvengerRepository</strong>, but we haven’t defined it anywhere else.</p><p>So, let’s try to quickly define it by creating an AvengerRepository.java file inside src/main/java/com/pagination_and_sorting/model/ folder and add the below code.</p><pre>package com.pagination_and_sorting.model;<br><br>import org.springframework.data.jpa.repository.JpaRepository;<br><br>public interface AvengerRepository extends JpaRepository&lt;Avenger, Integer&gt; {<br>}</pre><p>Here, our <strong>AvengerRepository</strong> is extending <strong>JpaRepository</strong> which would take Entity, Data type of Id of that entity as generic input values.</p><p>Finally, we are able to manage our avengers in the H2 database through the AvengerRepository interface.</p><p>Now, try to run the test case again, we’re gonna see magic now. Did we? Yes!</p><p>Hurrah, we have finally written the test case and made it pass!</p><p>Let’s try to code one more test case to test the <strong>findById()</strong> method of JpaRepository..!</p><pre>@Test<br>void shouldBeAbleToGetAvengerDetailsById() {<br>    Avenger ironman = new Avenger(&quot;Ironman&quot;, &quot;Iron Man&quot;, 2008);<br>    Avenger avenger = avengerRepository.findById(ironman.getId()).get();<br><br>    assertEquals(avenger.getId(), ironman.getId());<br>    assertEquals(avenger.getName(), ironman.getName());<br>    assertEquals(avenger.getIntroducedInYear(), ironman.getIntroducedInYear());<br>    assertEquals(avenger.getIntroducedInMovie(), ironman.getIntroducedInMovie());<br>}</pre><p>Now, try to run this test case using the IntelliJ shortcut (Ctrl + Shift + R).</p><p>It is passing, right? Yes, it is!</p><p>We are done with testing the Repository. Before moving forward, did you observe any code duplication in this file?</p><p>The definition of an ironman is repeated in both test cases, to avoid this we can make use of <strong>@BeforeEach</strong> annotation of Junit, to define all repetitive definitions inside a <strong>setUp()</strong> method where it would be called before running any test cases of class. To know more about it, you can refer to this <a href="https://www.baeldung.com/junit-before-beforeclass-beforeeach-beforeall">blog</a>.</p><p>The complete code of AvengerRepositoryTest.java is,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/45536051ad59cd2ae93e8004afcd56e2/href">https://medium.com/media/45536051ad59cd2ae93e8004afcd56e2/href</a></iframe><p>I would highly recommend you to write test cases like this when you have custom queries.</p><p>If you feel there are so many new words or annotations in the above file, please use google to know more about them.</p><p>Till this point, we are done with the Model Layer, our repository interface and entity class are ready, and now we have to dump some static data to the H2 database so as to fetch through APIs.</p><p>To do that we need to define a bean of <strong>CommandLineRunner</strong> inside a configured class of any type. Create a StaticDatabaseLoader.java file inside src/main/java/com/pagination_and_sorting/helpers/ folder and add the below code.</p><pre>package com.pagination_and_sorting.helpers;<br><br>import com.pagination_and_sorting.model.Avenger;<br>import com.pagination_and_sorting.model.AvengerRepository;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.boot.CommandLineRunner;<br>import org.springframework.context.annotation.Bean;<br>import org.springframework.context.annotation.Configuration;<br><br>import java.util.ArrayList;<br><br>@Configuration<br>public class StaticDatabaseLoader {<br>    @Autowired<br>    private AvengerRepository avengerRepository;<br><br>    @Bean<br>    public CommandLineRunner initDatabase() {<br>        return args -&gt; {<br>            String[] names = {&quot;Iron Man&quot;, &quot;Thanos&quot;, &quot;Captain America&quot;, &quot;Thor&quot;, &quot;Loki&quot;, &quot;Hulk&quot;, &quot;Captain Marvel&quot;, &quot;Spider Man&quot;, &quot;Black Widow&quot;, &quot;Hawkeye&quot;, &quot;Black Panther&quot;, &quot;Doctor Strange&quot;, &quot;Ant Man&quot;, &quot;Vision&quot;, &quot;Hulkbuster&quot;, &quot;War Machine&quot;, &quot;Nick Fury&quot;, &quot;Falcon&quot;, &quot;Winter Soldier&quot;, &quot;Ultron&quot;, &quot;Red Skull&quot;};<br>            String[] movies = {&quot;Iron Man&quot;, &quot;The Avengers&quot;, &quot;Captain America: The First Avenger&quot;, &quot;Thor&quot;, &quot;Thor&quot;, &quot;The Incredible Hulk&quot;, &quot;Captain Marvel&quot;, &quot;Captain America: Civil War&quot;, &quot;Iron Man 2&quot;, &quot;Thor&quot;, &quot;Captain America: Civil War&quot;, &quot;Doctor Strange&quot;, &quot;Ant Man&quot;, &quot;Avengers: Age of Ultron&quot;, &quot;Avengers: Age of Ultron&quot;, &quot;Iron Man&quot;, &quot;Iron Man&quot;, &quot;Captain America: The Winter Soldier&quot;, &quot;Captain America: The Winter Soldier&quot;, &quot;Avengers: Age of Ultron&quot;, &quot;Captain America: The First Avenger&quot;};<br>            int[] years = {2008, 2012, 2011, 2011, 2011, 2008, 2019, 2016, 2010, 2015, 2016, 2016, 2015, 2015, 2015, 2008, 2008, 2014, 2014, 2015, 2011};<br><br>            ArrayList&lt;Avenger&gt; avengers = new ArrayList&lt;&gt;();<br><br>            for (int i = 0; i &lt; 21; i++) {<br>                avengers.add(new Avenger(names[i], movies[i], years[i]));<br>            }<br><br>            avengerRepository.saveAll(avengers);<br>        };<br>    }<br>}</pre><p>We have written some logic to dump 21 avengers into the H2 database.</p><p>Now, everything is ready from the Model Layer end and we are all set to write some code to return a list of avengers in the Controller Layer.</p><p>To begin with writing the code, we first need to write the test case first, that is the thumb rule of TDD!</p><p>So, let’s try to create an AvengerControllerTest.java file inside src/test/java/com/pagination_and_sorting/controller/ folder and add the below code.</p><pre>package com.pagination_and_sorting.controller;<br><br>import com.pagination_and_sorting.model.Avenger;<br>import com.pagination_and_sorting.model.AvengerRepository;<br>import org.junit.jupiter.api.BeforeEach;<br>import org.junit.jupiter.api.Test;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;<br>import org.springframework.boot.test.mock.mockito.MockBean;<br>import org.springframework.test.web.servlet.MockMvc;<br>import org.springframework.test.web.servlet.ResultActions;<br><br>import java.util.Arrays;<br>import java.util.List;<br><br>import static org.mockito.Mockito.*;<br>import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;<br>import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;<br>import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;<br><br>@WebMvcTest(controllers = AvengerController.class)<br>public class AvengerControllerTest {<br>    @Autowired<br>    private MockMvc mockMvc;<br>    @MockBean<br>    private AvengerRepository avengerRepository;<br>    private List&lt;Avenger&gt; avengers;<br><br>    @BeforeEach<br>    void setUp() {<br>        Avenger ironman = new Avenger(&quot;Ironman&quot;, &quot;Iron Man&quot;, 2008);<br>        Avenger thor = new Avenger(&quot;Thor&quot;, &quot;Thor&quot;, 2011);<br>        avengers = Arrays.asList(ironman, thor);<br>    }<br><br>    @Test<br>    void shouldBeAbleToReturnListOfAvengers() throws Exception {<br>        when(avengerRepository.findAll()).thenReturn(avengers);<br><br>        ResultActions result = mockMvc.perform(get(&quot;/avengers&quot;));<br><br>        result.andExpect(status().isOk()).andDo(print());<br><br>        verify(avengerRepository, times(1)).findAll();<br>    }<br>}</pre><p>Now, try to run this test case using the IntelliJ shortcut (Ctrl + Shift + R).</p><pre>error: cannot find symbol<br>@WebMvcTest(controllers = AvengerController.class)<br>                          ^<br>  symbol: class AvengerController</pre><p>We are getting this error just because we are configuring our <strong>WebMvcTest</strong> with an undefined controller class.</p><p>So, let’s try to quickly create an AvengerController.java file inside src/main/java/com/pagination_and_sorting/controller/ folder and add the below code.</p><pre>package com.pagination_and_sorting.controller;<br><br>import com.pagination_and_sorting.model.AvengerRepository;<br>import org.springframework.web.bind.annotation.RestController;<br><br>@RestController<br>public class AvengerController {<br>    private final AvengerRepository avengerRepository;<br><br>    public AvengerController(AvengerRepository avengerRepository) {<br>        this.avengerRepository = avengerRepository;<br>    }<br>}</pre><p>Now, try running the test case again, did you get the same error? No, we are getting the below error.</p><pre>java.lang.AssertionError: Status expected:&lt;200&gt; but was:&lt;404&gt;</pre><p>We are getting this error because our test case is expecting 200 as status code but we are getting 404, which means our endpoint is not yet created inside the controller class. To do that, let’s try to add the below code.</p><pre>@GetMapping(&quot;/avengers&quot;)<br>public ResponseEntity&lt;?&gt; avengers() {<br>    List&lt;Avenger&gt; avengers = avengerRepository.findAll();<br>    return ResponseEntity.status(HttpStatus.OK).body(avengers);<br>}</pre><p>Now, try running the test case again, this time we could see it is passing, Congratulations!!!</p><p>We have tested the API through a test case but we can also test through a tool called <a href="https://www.postman.com/">postman</a>.</p><p>Before doing that, we need to start our application server. By default, Spring boot provides a tomcat server.</p><p>Now, we have to start it by going to the PaginationApplication.java inside src/main/java/com/pagination_and_sorting/ folder and use IntelliJ shortcut (Ctrl + Shift + R) to start the server.</p><p>Now, open the postman and hit our endpoint (<a href="http://localhost:3000/avengers">http://localhost:3000/avengers</a>), by default spring boot assigns 8080 as a port, but we have changed it to 3000 in the application.properties file if you remember!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kQNZAzCRu4-KxPR24UYi0A.png" /><figcaption>List of avengers as a Response from the GET request</figcaption></figure><p><strong>API — 2. List of avengers with Pagination</strong></p><p>By this, we have successfully completed the implementation of the first API. Let’s dive into building another API.</p><p>Before that, Let’s think if we can add any test cases for this API in the Model Layer.</p><p>No, because this API will also need the <strong>findAll()</strong> method of AvengerRepository for which we have already written test cases. So, no changes have to be added to the model package.</p><p>Let’s try to think if we can add any test cases for this API in the Controller Layer.</p><p>Yes, because even though the API will use the findAll() method of AvengerRepository, the result of the data should be paginated correctly.</p><p>Can you think, what is our next step if we have to add any logic?</p><p>As per the thumb rule of TDD, we need to add a test case first. So, add the below-mentioned test case inside AvengerControllerTest.java</p><pre>@Test<br>void shouldBeAbleToReturnListOfAvengersWithPagination() throws Exception {<br>    when(avengerRepository.findAll(pageRequest)).thenReturn(avengersPage);<br><br>    ResultActions result = mockMvc.perform(get(&quot;/avengers-with-pagination?pageNumber=0&amp;pageSize=1&quot;));<br><br>    result.andExpect(status().isOk())<br>          .andExpect(jsonPath(&quot;$.[0].id&quot;).value(avengers.get(0).getId()))<br>          .andExpect(jsonPath(&quot;$.[0].name&quot;).value(avengers.get(0).getName()))<br>          .andExpect(jsonPath(&quot;$.[0].introducedInMovie&quot;).value(avengers.get(0).getIntroducedInMovie()))<br>          .andExpect(jsonPath(&quot;$.[1].id&quot;).value(avengers.get(1).getId()))<br>          .andExpect(jsonPath(&quot;$.[1].name&quot;).value(avengers.get(1).getName()))<br>          .andExpect(jsonPath(&quot;$.[1].introducedInYear&quot;).value(avengers.get(1).getIntroducedInYear()))<br>          .andDo(print());<br><br>    verify(avengerRepository, times(1)).findAll(pageRequest);<br>}</pre><p>And run the test, you might have guessed the IntelliJ shortcut, if not use (Ctrl + Shift + R) to run the test case. I think you might have also guessed the output of this test case from the experience of previous test cases, which is a 404 assertion error!</p><p>Before creating that endpoint, let’s try to understand more about pagination.</p><blockquote>Spring Boot makes developer life easy to implement pagination.</blockquote><p>In pagination, the client would send his request in the form of <strong>pageNumber</strong> and <strong>pageSize</strong>. We have to send the response based on which pageNumber and how much data of pageSize the client wants.</p><p>But how are we going to fetch the data from the database as per the requested pageNumber and pageSize?</p><p>One basic idea is to collect all the data inside the database and divide it into multiple chunks as per the pageNumber and pageSize and send it to the client. Do you think there is any issue here?</p><p>Yes! Let’s say we have millions of data inside your database, we are fetching the whole data and dividing it into chunks. In this way, we are going to put lots of load on the database by fetching whole data for each and every request.</p><p>To rescue us from this kind of situation, Spring Data JPA acts as a super avenger by providing us with a built-in method to return the data in a pagination fashion from the database itself. But what is that built-in method which helps us?</p><p>The name of the method is <strong>findAll()</strong>, wait wait!</p><p>Have you heard about this method before? Yes, we have already used that method in the first API (getting a list of avengers without pagination and sorting), here you might have got one doubt. How is that same method going to help us in pagination?</p><p>To clear your doubt, even though the names are the same but the way of working is different because the <strong>findAll()</strong> method of the first API belongs to <strong>JpaRepository</strong> and it would return only the list of avengers without taking any input, whereas the <strong>findAll()</strong> method which we are going to use in this API actually belongs to <strong>PagingAndSortingRepository</strong> and return the Page of data by taking <strong>Pageable</strong> input which internally consists of pageNumber and pageSize.</p><p>So far what we have understood is, our first API used the findAll() method of JpaRepository by extending it with our custom <strong>AvengerRespository</strong>, that is completely fine!</p><p>For this API we are going to use the findAll() method of PagingAndSortingRepository but how are we going to use it? Do we have to create any custom Repository interface and extend PagingAndSortingRepository?</p><p>No, we aren’t needed to create any custom interfaces because JpaRepository is internally extending PagingAndSortingRepository so AvengerRepository alone would be helpful for us to get pagination data. You can refer to this <a href="https://www.baeldung.com/spring-data-repositories">blog</a> to understand repositories provided by the Spring data JPA.</p><pre>public interface JpaRepository&lt;T, ID&gt; extends PagingAndSortingRepository&lt;T, ID&gt;, QueryByExampleExecutor&lt;T&gt; {<br>}</pre><p>Enough of theory, now let’s try to resolve that 404 assertion error by creating an endpoint inside AvengerController.java. For that, append the below code.</p><pre>@GetMapping(&quot;/avengers-with-pagination&quot;)<br>public ResponseEntity&lt;?&gt; avengersWithPagination(<br>    @RequestParam(value = &quot;pageNumber&quot;, defaultValue = &quot;0&quot;, required = true) int pageNumber,<br>    @RequestParam(value = &quot;pageSize&quot;, defaultValue = &quot;10&quot;, required = true) int pageSize<br>) {<br>    PageRequest pageRequest = PageRequest.of(pageNumber, pageSize);<br>    Page&lt;Avenger&gt; avengersPage = avengerRepository.findAll(pageRequest);<br><br>    List&lt;Avenger&gt; avengers = avengersPage.getContent();<br><br>    return ResponseEntity.status(HttpStatus.OK).body(avengers);<br>}</pre><p>Here we have taken pageNumber and pageSize through <strong>URI query</strong> params, not through the <strong>URI path</strong> because the page is not a Resource, encoding the page information in the URI path is not the best idea because URI structure gonna disturbed but whereas encoding the paging information in a URI query gives convenience to the developers for better understanding.</p><p>We are encoding the pageNumber and pageSize inside <strong>PageRequest</strong> class and passing it to the findAll() method, but we have discussed that findAll() method would accept <strong>Pageable</strong> type, internally PageRequest is implementing the Pageable interface, so we can pass it to our findAll() method.</p><p>Now, try running the test case again, this time we could see it is passing, Congratulations again!!!</p><p>Let’s start the application server in the PaginationApplication.java<strong> </strong>file and test the API in postman.</p><p>Now, open the postman and hit our endpoint which is (<a href="http://localhost:3000/avengers-with-pagination?pageNumber=1&amp;pageSize=3">http://localhost:3000/avengers-with-pagination?pageNumber=1&amp;pageSize=3</a>), by default pageNumber starts with 0, here we are giving pageNumber as 1 which means we are requesting a second page with the size of 3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V8pAPyUXzs-h8hOASZ_fdw.png" /><figcaption>List of paginated avengers data as a Response from the GET request</figcaption></figure><p>Remaining two APIs were implemented in <a href="https://medium.com/@rasheed99/pagination-and-sorting-using-spring-boot-with-tdd-part-ii-281958b2d6fb">Part — II</a>.</p><p>Hope you have understood this post and please try to complete <a href="https://medium.com/@rasheed99/pagination-and-sorting-using-spring-boot-with-tdd-part-ii-281958b2d6fb">Part — II</a> as well.</p><p>You can check out the code on <a href="https://github.com/shaikrasheed99/springboot-pagination-and-sorting">Git Repository</a>.</p><p>Thanks for reading!!!</p><p>Feel free to connect with me on <a href="https://www.linkedin.com/in/shaikrasheed3011/">LinkedIn</a>!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c6533aa57a0c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pagination and Sorting using Spring Boot with TDD — Part II]]></title>
            <link>https://medium.com/@rasheed99/pagination-and-sorting-using-spring-boot-with-tdd-part-ii-281958b2d6fb?source=rss-d6b8ec72e7f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/281958b2d6fb</guid>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[pagination]]></category>
            <category><![CDATA[tdd]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Rasheed Shaik]]></dc:creator>
            <pubDate>Sun, 20 Nov 2022 14:38:04 GMT</pubDate>
            <atom:updated>2022-11-22T17:32:41.932Z</atom:updated>
            <content:encoded><![CDATA[<h3>Pagination and Sorting using Spring Boot with TDD — Part II</h3><p>This post is continuation of <a href="https://medium.com/@rasheed99/pagination-and-sorting-using-spring-boot-with-tdd-part-i-c6533aa57a0c">Part — I</a> of Pagination and Sorting series, please make sure you have completed it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2lzQnqC6TSz5FJ6qNvg-mA.png" /></figure><p>In the <a href="https://medium.com/@rasheed99/pagination-and-sorting-using-spring-boot-with-tdd-part-i-c6533aa57a0c">Part — I</a>, we have implemented two APIs. Now, in this post we are going to implement remaining two APIs.</p><p><strong>API — 3. List of avengers with Sorting on a particular field</strong></p><p>By this, we have successfully completed the implementation of the second API (list of avengers with pagination). Let’s dive into building another API.</p><p>Do we have to add any test cases for this API in the Controller Layer? Yes, because even though the API will use the findAll() method of AvengerRepository, the result of the data should be sorted correctly.</p><p>As per the thumb rule of TDD, we need to add a test case first. So, add the below test case inside AvengerControllerTest.java</p><pre>@Test<br>void shouldBeAbleToReturnListOfAvengersWithSorting() throws Exception {<br>    when(avengerRepository.findAll(Sort.by(Sort.Direction.DESC, &quot;name&quot;))).thenReturn(avengers);<br><br>    ResultActions result = mockMvc.perform(get(&quot;/avengers-with-sorting?sort=name,desc&quot;));<br><br>    result.andExpect(status().isOk())<br>          .andExpect(jsonPath(&quot;$.[0].id&quot;).value(avengers.get(0).getId()))<br>          .andExpect(jsonPath(&quot;$.[0].name&quot;).value(avengers.get(0).getName()))<br>          .andExpect(jsonPath(&quot;$.[0].introducedInMovie&quot;).value(avengers.get(0).getIntroducedInMovie()))<br>          .andExpect(jsonPath(&quot;$.[1].id&quot;).value(avengers.get(1).getId()))<br>          .andExpect(jsonPath(&quot;$.[1].name&quot;).value(avengers.get(1).getName()))<br>          .andExpect(jsonPath(&quot;$.[1].introducedInYear&quot;).value(avengers.get(1).getIntroducedInYear()))<br>          .andDo(print());<br><br>    verify(avengerRepository, times(1)).findAll(Sort.by(Sort.Direction.DESC, &quot;name&quot;));<br>}</pre><p>And run the test case using IntelliJ shortcut (Ctrl + Shift + R). We have got a 404 assertion error because we have not created a related endpoint yet.</p><p>For sorting also we are going to use the findAll() method of PagingAndSortingRepository. This method can take <strong>Sort</strong> objects as input. So, we pass an instance of the Sort class by encoding the name of the field through the static <strong>Sort.by()</strong> method.</p><p>Now let’s try to resolve that 404 assertion error by creating an endpoint inside AvengerController.java and append the below code.</p><pre>@GetMapping(&quot;/avengers-with-sorting&quot;)<br>public ResponseEntity&lt;?&gt; avengersWithSorting(<br>    @RequestParam(value = &quot;sort&quot;, defaultValue = &quot;id, asc&quot;, required = true) String[] sortingParams<br>) {<br>    String field = sortingParams[0];<br>    String sortingDirection = sortingParams[1];<br><br>    Sort.Direction direction = sortingDirection.equals(&quot;asc&quot;) ? Sort.Direction.ASC : Sort.Direction.DESC;<br><br>    List&lt;Avenger&gt; avengers = avengerRepository.findAll(Sort.by(direction, field));<br><br>    return ResponseEntity.status(HttpStatus.OK).body(avengers);<br>}</pre><p>Here we have taken the name of the field and direction of sorting through request params. We have multiple ways to sort data in a particular direction.</p><ul><li>Using Enumeration</li></ul><blockquote>Sort.by(Sort.Direction.DESC, field)</blockquote><blockquote>Sort.by(Sort.Direction.<em>ASC</em>, field)</blockquote><ul><li>Using methods</li></ul><blockquote>Sort.by(field).ascending()</blockquote><blockquote>Sort.by(field).descending()</blockquote><ul><li>We can also sort multiple fields at a time</li></ul><blockquote>Sort.by(fieldOne).ascending().and(Sort.by(fieldTwo).descending())</blockquote><p>Now, try running the test case again, this time we could see it is passing, Congratulations again!!!</p><p>Let’s start the application server in the PaginationApplication.java<strong> </strong>file and test the API in postman.</p><p>Now, open the postman and hit our endpoint (<a href="http://localhost:3000/avengers-with-sorting?sort=introducedInYear,desc">http://localhost:3000/avengers-with-sorting?sort=introducedInYear,desc</a>), here we are giving introducedInYear as a field and desc as sorting direction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1lxyMV57W_oBdsBu0AYubw.png" /><figcaption>List of sorted avengers as a Response from the GET request</figcaption></figure><p><strong>API — 4. List of avengers with Pagination and Sorting</strong></p><p>As of now, we have successfully completed the implementation of the third API (list of avengers with sorting). Let’s dive into building another API.</p><p>As like earlier APIs, add the below test case in AvengerControllerTest.java</p><pre>@Test<br>void shouldBeAbleToReturnListOfAvengersWithPaginationAndSorting() throws Exception {<br>    when(avengerRepository.findAll(pageRequestWithSorting)).thenReturn(avengersPage);<br><br>    ResultActions result = mockMvc.perform(get(&quot;/avengers-with-pagination-and-sorting?pageNumber=0&amp;pageSize=1&amp;sort=name,desc&quot;));<br><br>    result.andExpect(status().isOk())<br>          .andExpect(jsonPath(&quot;$.[0].id&quot;).value(avengers.get(0).getId()))<br>          .andExpect(jsonPath(&quot;$.[0].name&quot;).value(avengers.get(0).getName()))<br>          .andExpect(jsonPath(&quot;$.[0].introducedInMovie&quot;).value(avengers.get(0).getIntroducedInMovie()))<br>          .andExpect(jsonPath(&quot;$.[1].id&quot;).value(avengers.get(1).getId()))<br>          .andExpect(jsonPath(&quot;$.[1].name&quot;).value(avengers.get(1).getName()))<br>          .andExpect(jsonPath(&quot;$.[1].introducedInYear&quot;).value(avengers.get(1).getIntroducedInYear()))<br>          .andDo(print());<br><br>    verify(avengerRepository, times(1)).findAll(pageRequestWithSorting);<br>}</pre><p>And run the test case using IntelliJ shortcut (Ctrl + Shift + R). We have got a 404 assertion error because we have not created a related endpoint yet.</p><p>In the pagination API, we have passed a Pageable object to the findAll() method for pagination, but in this API we need pagination along with sorting as well. How are we going to do it?</p><p>Are we going to query the pagination result through findAll() method and apply to sort explicitly on it? But for sorting also, we have used findAll() method by passing a Sort object as input. Did you observe anything over here?</p><p>Since pagination and sorting APIs have used findAll() method, can we pass both Pageable and Sort objects as inputs to findAll() method for results with pagination and sorting?</p><p>No, that is a bad idea. We cannot pass two objects at once to the findAll() method, instead, we can wrap the Sort object inside the Pageable request object and pass it to the findAll() method. Alright, let’s try to implement this way.</p><p>Now let’s try to resolve that 404 assertion error by creating an endpoint inside AvengerController.java and append the below code.</p><pre>@GetMapping(&quot;/avengers-with-pagination-and-sorting&quot;)<br>public ResponseEntity&lt;?&gt; avengersWithPaginationAndSorting(<br>    @RequestParam(value = &quot;pageNumber&quot;, defaultValue = &quot;0&quot;, required = true) int pageNumber,<br>    @RequestParam(value = &quot;pageSize&quot;, defaultValue = &quot;10&quot;, required = true) int pageSize,<br>    @RequestParam(value = &quot;sort&quot;, defaultValue = &quot;id, asc&quot;, required = true) String[] sortingParams<br>) {<br>    String field = sortingParams[0];<br>    String sortingDirection = sortingParams[1];<br>    Sort.Direction direction = sortingDirection.equals(&quot;asc&quot;) ? Sort.Direction.ASC : Sort.Direction.DESC;<br>    PageRequest pageRequest = PageRequest.of(pageNumber, pageSize, Sort.by(direction, field));<br><br>    Page&lt;Avenger&gt; avengersPage = avengerRepository.findAll(pageRequest);<br><br>    List&lt;Avenger&gt; avengers = avengersPage.getContent();<br><br>    return ResponseEntity.status(HttpStatus.OK).body(avengers);<br>}</pre><p>Now, try running the test case again, this time you could see it is passing, Congratulations again!!!</p><p>Let’s start the application server in the PaginationApplication.java<strong> </strong>file and test the API in postman.</p><p>Now, open the postman and hit our endpoint (<a href="http://localhost:3000/avengers-with-pagination-and-sorting?pageNumber=0&amp;pageSize=3&amp;sort=id,">http://localhost:3000/avengers-with-pagination-and-sorting?pageNumber=0&amp;pageSize=3&amp;sort=id, desc</a>), here we are giving pageNumber as 0 which means we are requesting the first page with the size of 3 and id as field and desc as sorting direction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DnERK07hO7oJGBjbC-bd6A.png" /><figcaption>List of sorted and paginated avengers as a Response from the GET request</figcaption></figure><p>The complete code of AvengerControllerTest.java is,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c2e59da7cbe3bf3f90cfd9fc704b6125/href">https://medium.com/media/c2e59da7cbe3bf3f90cfd9fc704b6125/href</a></iframe><p>The complete code of AvengerController.java is,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/15a48ff4543aace8a7a05abcb245b897/href">https://medium.com/media/15a48ff4543aace8a7a05abcb245b897/href</a></iframe><p>If you feel there are so many new words or annotations in the above file, please use google to know more about them.</p><p>This is all about pagination and sorting using Spring Boot with TDD.</p><p>Hope you have understood this post and please try to implement it in your projects.</p><p>You can check out the code on <a href="https://github.com/shaikrasheed99/springboot-pagination-and-sorting">Git Repository</a>.</p><p>Thanks for reading!!!</p><p>Feel free to connect with me on <a href="https://www.linkedin.com/in/shaikrasheed3011/">LinkedIn</a>!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=281958b2d6fb" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>