<?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 George Benjamin on Medium]]></title>
        <description><![CDATA[Stories by George Benjamin on Medium]]></description>
        <link>https://medium.com/@msdcconnect?source=rss-3df1975af924------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*XQHM9D6Suet5JHxp4m9oZQ.jpeg</url>
            <title>Stories by George Benjamin on Medium</title>
            <link>https://medium.com/@msdcconnect?source=rss-3df1975af924------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 19:37:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@msdcconnect/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[Common mistakes that are making your web apps insecure, and how to fix them.]]></title>
            <link>https://medium.com/@msdcconnect/common-mistakes-that-are-making-your-web-apps-insecure-and-how-to-fix-them-4e9104cd24c1?source=rss-3df1975af924------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e9104cd24c1</guid>
            <category><![CDATA[hacking]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[web-security]]></category>
            <category><![CDATA[security]]></category>
            <dc:creator><![CDATA[George Benjamin]]></dc:creator>
            <pubDate>Tue, 13 Sep 2022 20:18:43 GMT</pubDate>
            <atom:updated>2022-09-14T15:24:14.982Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K--C6DY3s43i464yEOHxYA.jpeg" /><figcaption>Photo by Ketut Subiyanto</figcaption></figure><p>The internet has become an integral part of our lives as humans. We rely on web apps to perform daily activities like shopping, communicating with friends and family, collaborating with colleagues, learning, and many more. A successful web app must be reliable, secure, and fast. Compromising on any of these qualities can result in a catastrophe.</p><p>In this article, I will share some widespread mistakes I’ve seen many developers make that compromise the security, reliability, and performance of web apps. Additionally, I provide suggestions on how these mistakes can be corrected. While security is a very broad topic, I’ll only concentrate on application-level security i.e the web app and not the infrastructure where the web app is deployed.</p><p>I would include some code samples, which will be written in NodeJS. However, knowledge of NodeJS is not necessary. The same principle applies to other languages.</p><h4>Table of content</h4><ul><li><a href="#4a7f">Trusting the user</a><br> — <a href="#c3c7">Input validation best practices</a></li><li><a href="#a8bc">Including sensitive information in responses</a></li><li><a href="#38ec">Authentication flaws</a><br> — <a href="#aafb">Problem with JWTs</a><br> — <a href="#7ac0">Implementing authentication using sessions</a><br> — <a href="#b190">Best Practices when using sessions for authentication</a></li><li><a href="#9291">Rate limiting</a></li><li><a href="#39ed">Multifactor authentication (MFA)</a></li><li><a href="#73dd">Inadequate access control</a></li><li><a href="#da2a">Insufficient logging</a></li></ul><h4>1. Trusting the user</h4><p>Trust no one, especially your user. All web apps accept some form of input, for example, an email, phone number, etc. Many developers assume users would provide the correct data in the proper format. However, an attacker can deliberately enter malicious data into your web app. Consider this example.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d78cfc3a0f206c98ea6348e1ae7ed105/href">https://medium.com/media/d78cfc3a0f206c98ea6348e1ae7ed105/href</a></iframe><p>Instead of sending a legitimate email, an attacker can send a value like {email: {$exists: true}}. So, rather than checking if an email exists as intended, this retrieves all user accounts with an email, giving the attacker access to tonnes of sensitive information. If user inputs aren’t properly validated and sanitized, an attacker can gain access to restricted data. This is referred to as an injection attack.</p><p><strong>Input validation best practices<br></strong>1. Perform input validation on the client (e.g the user’s browser) and the server. <br>2. Use a popular validation library for your language/framework instead of writing your custom validation logic.<br>3. Sanitize all user inputs before using them as values in your database queries.</p><h4>2. Including sensitive information in responses</h4><p>Sometimes, web apps unknowingly return sensitive data in their responses e.g a user’s password, token, etc. Sanitizing responses is as equally crucial as sanitizing user input. Make sure you are returning only data the client (user interface) needs to function correctly, nothing more.</p><h4>3. Authentication flaws</h4><p>Authentication is an essential part of any web app. Authentication verifies the identity of a user. A typical web app would require users to enter an email (or username) and password before granting access to its features. A popular method of implementing authentication in web apps is <a href="https://jwt.io/introduction">JSON Web Tokens (JWTs)</a>. The use of JWT for authentication is prevalent because it is simple to use, compact and self-contained.</p><p><strong>The Problem with JWTs<br></strong>JWTs aren’t very secure. Some common flaws made when using JWTs are:</p><ol><li>Including too much private and sensitive information in a JWT: This information can easily be obtained by decoding the JWT.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tXW-ybKW1cwFfQJN1XOJgw.png" /></figure><p>2. Not setting an expiration for JWTs: When the developer does not explicitly set the expiry of a JWT, the JWT is valid forever. This is a serious security risk that can lead to grave consequences.</p><p>3. Failure to invalidate existing JWTs: JWTs have a fixed expiration. This means they are valid until that expiration is reached. Invalidating a JWT before it expires is complicated. If an attacker obtains a valid JWT, they can steal the identity of the user the JWT was issued to until the JWT expires.</p><p><strong>Implementing authentication using sessions<br></strong>Sessions provide a more secure way to implement authentication in your web app. When a user logs in, the details of the authenticated user, along with a randomly generated session id, are stored in a persistent store which could be a database. The session id is returned to the client. Every time a client makes a request, it includes the session id in the request. The server uses the session id to retrieve the user’s authentication state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vh-1_Slhvk1xMK5T9LkoCw.png" /><figcaption>Authentication using sessions</figcaption></figure><p>Since the session state would need to be retrieved on each request to the app, the session data should be stored in a fast and efficient data store like Redis. Redis is an in-memory data store that can be used as a cache, database, streaming engine, and message broker. Redis can exponentially increase the speed of session lookups, which makes your application faster. Thousands of companies serving millions of users use Redis for session storage because of its performance benefits.</p><p>The easiest way to get started with Redis is by creating an account on <a href="https://redis.com/try-free/">Redis Cloud</a>. Redis Cloud provides on-demand access to a Redis database in a couple of minutes.</p><p>Here’s a sample code snippet demonstrating how to implement authentication with sessions, using Redis as a session store.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6678b1941c7829e785b068a7a14fdfa5/href">https://medium.com/media/6678b1941c7829e785b068a7a14fdfa5/href</a></iframe><p>Redis Insight is an extremely helpful GUI tool for interacting and managing data stored in Redis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zoc2Diz0ZLlgDePUOOYVvg.png" /><figcaption>Viewing sessions in Redis using RedisInsight</figcaption></figure><p><strong>Best Practices when using sessions for authentication<br></strong>1. Always regenerate sessions after a user logs in to prevent session fixation attacks.<br>2. Destroy a user’s session when they log out.<br>3. When a user updates or resets their password, destroy all active user sessions. In the code sample above, I prefixed the session id with the user’s id for this purpose. To destroy all a user’s active sessions, I retrieve all session ids beginning with the user’s id and delete them from Redis.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/62329d4bfa92b208f6d2b706904ee607/href">https://medium.com/media/62329d4bfa92b208f6d2b706904ee607/href</a></iframe><h4>4. Rate limiting</h4><p>An attacker might try to gain access to restricted data by trying many combinations of usernames and passwords, with the hope of eventually guessing the correct one. This is known as <a href="https://www.imperva.com/learn/application-security/brute-force-attack/">brute forcing</a>.</p><p>In some other cases, an attacker might flood your web app with a huge amount of traffic, which could use up your available server resources, leaving your web app inaccessible to its intended users. This is referred to as a <a href="https://www.cloudflare.com/en-gb/learning/ddos/what-is-a-ddos-attack/">Denial of Service</a> attack.</p><p>A proper strategy to secure your web apps against these attacks is rate-limiting. Rate limiting restricts the number of requests a client can make to your web app within a specific time window. For example, you can only allow a particular user to make 100 requests within five (5) minutes. When the user exceeds the allowed number of requests, all subsequent requests are rejected or delayed. The purpose of rate limiting is to improve the availability of your web app by protecting it from excessive use/abuse.</p><p>In order to implement rate limiting, we store the user’s IP address, along with the number of requests they have made in a time period. Each time a user makes a request, we retrieve the current number of requests using their IP address and check that it is not above our limit. An ideal location to store this data is in a cache — Redis. Here’s a sample code to implement rate limiting in your web app.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c4fc0184196fb85b436cdb0da0f10fdf/href">https://medium.com/media/c4fc0184196fb85b436cdb0da0f10fdf/href</a></iframe><p>Sensitive functions of your application such as login, password reset, etc must be rate limited.</p><h4>5. Multi-factor authentication (MFA)</h4><p>Another strategy to prevent brute force and improve the security of your web app is multi-factor authentication. Instead of relying solely on one form of authentication, typically an email and password, additional authentication layers are added.</p><p>For example, after a user successfully inputs the correct email and password, an OTP (One-Time-Password) is sent to the user’s phone number. The user must then provide the OTP before being granted access to the web app. So even when an attacker has access to a user’s login credentials, they would be unable to access the user’s account. This can easily be implemented using Redis.</p><p>Here’s a code sample of how MFA can be implemented using Node and Redis.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d702f4f51678e954fe15526a0fe0549/href">https://medium.com/media/3d702f4f51678e954fe15526a0fe0549/href</a></iframe><h4>6. Inadequate access control</h4><p>While authentication verifies the identity of a user, authorization determines if a user should be granted access to a specific resource or functionality in a web app. Authorization determines what a user can do. The lack of a proper authorization strategy would give users unrestricted access to data stored on a web app. How would you feel if any Amazon user could access your order history? Scary right?</p><p>Role Based Access Control (RBAC) is a possible solution to this problem. Users of your web app are assigned roles. Each role is granted a set of permissions that specify the actions allowed. Whenever a request is sent to the web app, verify that the role assigned to a user has the necessary permission to perform the requested action.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7d3853947a2710fdb1dd1e15a8447a99/href">https://medium.com/media/7d3853947a2710fdb1dd1e15a8447a99/href</a></iframe><h4>7. Insufficient logging and monitoring</h4><p>Logging is to a web app what security cameras are to a building. Logging is crucial for detecting and responding to security attacks. Logs are simply messages that inform you about the state of the web app. Logs can also inform you about errors that occur in your web app. For example, logs can be written for activities like log-ins, password reset, payments, etc.</p><p>Application logs should be stored so they can be accessed. Several logging solutions exist. For example Elastic Search +Logstash + Kibana stack (ELK), Elastic Search + FluentD + Kibana stack (EFK), Promtail + Loki + Grafana stack, etc. You can even use RedisJSON to store logs and RedisSearch for analyzing logs. Do proper research and pick a solution that works best for you.</p><h4>Conclusion</h4><p>The security of your web app is crucial to its success. Thank you for reading, I hope it was worth it. To learn more about how you can improve the security of your app, check out <a href="https://owasp.org/">The Open Web Application Security Project (OWASP)</a>.</p><p>This post is in collaboration with Redis.</p><p><strong>Learn more:<br>. </strong><a href="https://redis.info/3NBGJRT">Try Redis Cloud for free</a><br>. <a href="https://redis.info/3Ga9YII">Watch this video on the benefits of Redis Cloud over other Redis providers</a><br>. <a href="https://redis.info/3LC4GqB">Redis Developer Hub — tools, guides, and tutorials about Redis</a><br>. <a href="https://redis.info/3wMR7PR">RedisInsight Desktop GUI</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e9104cd24c1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My favorite sitcoms of all time]]></title>
            <link>https://medium.com/@msdcconnect/my-favorite-sitcoms-of-all-time-debe3c4c002c?source=rss-3df1975af924------2</link>
            <guid isPermaLink="false">https://medium.com/p/debe3c4c002c</guid>
            <dc:creator><![CDATA[George Benjamin]]></dc:creator>
            <pubDate>Sat, 03 Sep 2022 16:05:40 GMT</pubDate>
            <atom:updated>2023-03-31T19:40:52.351Z</atom:updated>
            <content:encoded><![CDATA[<p>Here are my top sitcoms in no particular order.</p><ol><li>Curb Your Enthusiasm</li><li>The Office (US)</li><li>Brooklyn 99</li><li>Superstore</li><li>Parks and Recreation</li><li>Scrubs</li><li>Space Force</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=debe3c4c002c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Important Tips for Acing your Certified Kubernetes Administrator Exam]]></title>
            <link>https://medium.com/@msdcconnect/important-tips-for-acing-your-certified-kubernetes-administrator-exam-23cc213ca99a?source=rss-3df1975af924------2</link>
            <guid isPermaLink="false">https://medium.com/p/23cc213ca99a</guid>
            <category><![CDATA[cka]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[certified-kubernetes]]></category>
            <category><![CDATA[linux-foundation]]></category>
            <dc:creator><![CDATA[George Benjamin]]></dc:creator>
            <pubDate>Tue, 09 Aug 2022 19:01:31 GMT</pubDate>
            <atom:updated>2022-08-09T19:06:01.645Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*9VnnxTyiLdUGDuK6XVUIfA.png" /></figure><p>If you’re thinking about writing the Certified Kubernetes Administrator Exam, this article is for you! I would be sharing some valuable tips that would help you ace your exam. The CKA exam is often regarded as a “tough one”, however, it doesn’t have to be so for you.</p><p>Whether you’re new to Kubernetes or you already have adequate experience working with Kubernetes, I believe some of these tips would help you a great deal. Although studying is important, there are a lot more factors that determine how well you perform in your CKA exam. Let’s get right to it.</p><h4>Studying</h4><p>There are a tonne of learning resources for Kubernetes. If you’re new to Kubernetes, this can be quite overwhelming. Which one should you choose? Should you get a paid course?</p><p>Well, I decided to pay for the <a href="https://training.linuxfoundation.org/training/kubernetes-fundamentals/">Kubernetes Fundamentals (LFS258)</a> course from the Linux foundation for $299. While the course is very thorough, if I could go back in time, I probably wouldn’t have bought it for the following reasons:</p><ul><li>It’s not cheap.</li><li>It’s 90% text. There are a couple of introductory videos, but most of the course content is text. If you prefer listening and watching someone teach to reading, don’t bother buying this.</li><li>After paying $299, you’re not given an environment to practice what you’ve learned. You’ll have to practice elsewhere.</li></ul><p>If you have the money and don’t mind the issues I talked about, please purchase it, you would learn a lot. However, if like me, you prefer to save money, here are some great, high-quality resources I recommend.</p><ul><li><a href="https://kodekloud.com/">KodeKloud</a>: I randomly stumbled on KodeKloud while scrolling on social media, I decided to check it out, and it’s awesome! Their <a href="https://kodekloud.com/courses/certified-kubernetes-administrator-cka/">CKA course</a> is very detailed! Their instructors do an excellent job of simplifying seemingly complex Kubernetes concepts. In addition to that, you get a lab environment where you can practice what you learn. The best part is I paid $1/month. That’s very good value for $1. I highly recommend.</li><li><a href="https://training.linuxfoundation.org/training/introduction-to-kubernetes/">Introduction to Kubernetes (LFS158x)</a>: This course is also provided by the Linux foundation, and it’s free. It’s a very good course to begin your Kubernetes journey.</li><li><a href="https://kube.academy/courses">KubeAcademy</a>: The courses are taught by experts. They give you a deep understanding of containerization. Most of their content is free, I didn’t have to pay for any of the courses I took.</li></ul><p>Kubernetes has great <a href="https://kubernetes.io/docs">documentation</a>. Reference the documentation as often as possible.</p><h4>Stop using Minikube</h4><p><a href="https://minikube.sigs.k8s.io/docs/start/">Minikube</a> is a great tool for learning Kubernetes. If you’re planning on taking the CKA exam, I can assume it’s because you want to manage a company’s workload in production. No company uses Minikube to run its production workloads. So you need to get comfortable working with multi-node production Kubernetes clusters. The only way to get comfortable with something is by doing it often.</p><p>Practice setting up basic clusters (single control plane with multiple worker nodes), highly available clusters, upgrading clusters, etc. I use <a href="https://m.do.co/c/a077a1287bdb">Digital Ocean</a> to provision VPS for deploying my clusters. I love Digital ocean because of its simplicity. When you register on Digital Ocean using <a href="https://m.do.co/c/a077a1287bdb">this link</a>, you get $100 free credit for 60 days! Digital Ocean also provides a <a href="https://www.digitalocean.com/products/kubernetes">managed Kubernetes service</a> for setting up a k8s cluster in a few clicks. Although this offering is more restrictive as you no longer have the responsibility of managing the control plane, it’s very handy when you want to quickly provision a cluster.</p><h4>Practice A LOT</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/695/1*lAUOkP9kjOsLe04FtJK0EQ.jpeg" /></figure><p>You should already know that the CKA exam is a practical one. The only way to get good at a skill is to practice consistently. Practice deploying applications on the clusters you’ve provisioned. When you run into errors (you definitely would), debug and fix them. You will learn a lot from the errors you encounter. Practice your kubectl commands. Imperative commands will save you a lot of time. Additionally, practice</p><ul><li>Linux commands like systemctl, journalctl, service, etc</li><li>Vim: Try to use Vim as much as possible. While it might be faster and easier for you to write manifest files (YAML) in your favourite text editor, the only editor provided by the CKA exam is Vim. So, the more farmiliar you are with Vim, the faster you are, and the better your chances of passing. Vim has a lot of shortcuts that can make your life easier, learn about them.</li></ul><p>You can use the <a href="https://github.com/cncf/curriculum">CKA curriculum</a> as a guide for practicing.</p><h4>Get familiar with the Exam interface</h4><p>In June 2022, the Linux Foundation updated the exam interface for the CKA exam. You can read more about it <a href="https://training.linuxfoundation.org/blog/update-on-certification-exam-proctoring-migration/">here</a>. The new platform uses a Linux (XFCE) Remote Desktop which can only be accessed via the PSI Secure Browser. You can’t use Chrome anymore, say goodbye to all your bookmarks.</p><p>Fortunately, when you pay for your CKA exam, you get 2 free attempts at an exam simulator, provided by<a href="https://killer.sh/"> Killer.sh</a>. PLEASE, use this. It is very important. Killer.sh provides a very close replica of the real exam. This would help you get comfortable with the interface, practice copy and pasting, etc. Killer.sh also provides practice questions to help you prepare for your exam. The practice questions are more difficult than the real exam, so if you can comfortably answer 80% of the questions correctly, you’re good to go.</p><h4>Get good internet!</h4><p>As I mentioned earlier, the CKA exam uses a remote desktop. If you have poor internet, please don’t bother taking the exam because you would likely go insane because of the lag. An internet speed of at least 50Mbps should be sufficient.</p><h4>Get a good camera</h4><p>As part of your check-in process, you would be required to take a photo of your Government issued ID card to verify your identity. For my exam, I bought the cheapest webcam I could find😅. That was a very bad decision. I spent over 30 minutes trying to take a clear picture of my ID. The proctor kept rejecting all the pictures I took. I was almost frustrated. I spent over an hour for my check-in because I had a bad camera. Please don’t let that happen to you. Make sure your webcam can take clear pictures of your ID.</p><h4>Read the exam instructions</h4><p>Before taking your exam, make sure you have read and understood the candidate handbook and exam instructions. Don’t take those instructions for granted. Make sure your exam location meets all the requirements before starting.</p><p>During the exam, it is important that you read and understand the questions before starting the task. The exam uses different contexts for different questions. Always remember to switch to the right context before performing your task.</p><h4>One last thing</h4><p>Relax. Don’t stress about it. If you follow the tips provided in this article, you’d do just fine!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*NGctbR7fFFQwBG5LPeX54A.jpeg" /></figure><p>If you enjoyed this article, please leave a clap. You can also connect with me on <a href="https://www.linkedin.com/in/georgeben/">LinkedIn</a>, I would love to hear from you. Follow <a href="https://twitter.com/memenetes">memenetes</a> for funny Kubernetes memes. Thank you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=23cc213ca99a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing a scheduling feature in your web app using RabbitMQ]]></title>
            <link>https://medium.com/@msdcconnect/implementing-a-scheduling-feature-in-your-web-app-using-rabbitmq-2bd47b20c6eb?source=rss-3df1975af924------2</link>
            <guid isPermaLink="false">https://medium.com/p/2bd47b20c6eb</guid>
            <category><![CDATA[task-queues]]></category>
            <category><![CDATA[scheduling]]></category>
            <category><![CDATA[rabbitmq]]></category>
            <dc:creator><![CDATA[George Benjamin]]></dc:creator>
            <pubDate>Sun, 22 Aug 2021 18:15:08 GMT</pubDate>
            <atom:updated>2021-08-22T18:15:08.003Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/728/1*vWQTg0WwD9MSkBQijCFI7w.jpeg" /></figure><p>There are certain scenarios when you would want to enable users to schedule actions on your app that should happen sometime in the future. Some common examples are:</p><ul><li>Social media apps like Twitter, allow users to schedule a tweet they want to be posted at a certain date.</li><li>Some stock trading apps allow users to automatically buy/sell a certain stock at a specific time in the future.</li><li>An appointment app might allow users to set reminders for certain events/meetings.</li></ul><h4>Who should read this?</h4><p>This is not an introduction to RabbitMQ. It is expected that you at least understand the basics of RabbitMQ. For an introduction to RabbitMQ, <a href="https://www.rabbitmq.com/getstarted.html">read here</a>. The example code used in this article is written in NodeJS. Although knowledge of NodeJS would be helpful, it is not required.</p><h4>Prerequisites</h4><p>The sample code shown uses RabbitMQ v.3.9.3. It is recommended that you have at least RabbitMQ v.3.8.16 and Erlang 23.2+ installed.</p><h4>Introduction</h4><p>Like everything in software development, there are several ways to implement scheduling. A common way is using <a href="https://en.wikipedia.org/wiki/Cron">cronjobs</a>. Cronjobs are created to run at specific known times/intervals. For example, 8 am every Sunday. However, we can’t know beforehand what time a user would want to schedule an action, so, we could set a cron job to run every minute, checking if there are any scheduled actions to execute.</p><p>While this works, I don’t think it’s very efficient. Running a cron job every minute is quite expensive: consumes memory, CPU, I/O resources (database calls). RabbitMQ offers a straightforward solution for implementing scheduling.</p><h4>How it works</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*stfIosZ4W9yH2vDdtseMiA.png" /></figure><p>The basic idea behind this implementation is delaying the execution of an action till the time specified by the user. Let me explain a bit more. The current time while writing this article is 21st August 2021, 11:10 pm. Imagine a user schedules a tweet to be posted on 23rd August 2021, 11:50 am. We need to calculate the difference between the current time, and the desired time the tweet should be posted. In this example, the time difference is 1 day, 12 hours, and 39 minutes. This means we should delay posting the user’s tweet by 1 day, 12 hours, 39 minutes.</p><p>When a user schedules an action, instead of executing that action immediately, we create a message stating the action the user wants to perform, publish it to RabbitMQ, then instruct RabbitMQ to hold that message from “now” till the scheduled time. Once the wait is over, RabbitMQ would deliver the message back to your app for execution. Makes sense?</p><p>There are a couple of ways to delay messages in RabbitMQ. In this article, we would use the <a href="https://github.com/rabbitmq/rabbitmq-delayed-message-exchange/">RabbitMQ Delayed Message Plugin</a>.</p><h4>Installing the plugin</h4><p>To install the RabbitMQ delayed messages plugin, go to the <a href="https://www.rabbitmq.com/community-plugins.html">Community Plugins</a> page, search for “<em>rabbitmq_delayed_message_exchange</em>”. Click on releases. This should take you to the plugin’s <a href="https://github.com/rabbitmq/rabbitmq-delayed-message-exchange/releases">Github release history</a>. Download your preferred version of the release. Make sure the version you download is compatible with the RabbitMQ version you have installed.</p><p>After downloading the plugin (.ez file), copy it into the RabbitMQs plugins folder. If you don’t know where the plugins directory is located, <a href="https://www.rabbitmq.com/installing-plugins.html">this might be helpful</a>. On my computer (Mac OS Catalina), my plugins directory is located at <em>“/usr/local/Cellar/rabbitmq/3.9.3/plugins”.</em></p><p>Once you have copied the plugin into the plugins directory, enable the plugin by running this command in your terminal</p><pre>rabbitmq-plugins enable rabbitmq_delayed_message_exchange</pre><h4>Creating a delay exchange</h4><p>The RabbitMQ Delayed Message plugin adds a special exchange type (called “<strong>x-delayed-message</strong>”) to RabbitMQ where messages routed by that exchange can be delayed.</p><p>To create a delay exchange, declare an exchange and set the type to <em>“x-delayed-message” </em>like so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/64a182607bd64c29e313f73f8e14f794/href">https://medium.com/media/64a182607bd64c29e313f73f8e14f794/href</a></iframe><p>Notice in the options, we provided an <em>“x-delayed-type”</em> argument. The <em>‘x-delayed-type’</em> sets the behavior of the exchange. In this case, we want the exchange to behave like a direct exchange. You can set the value of <em>“x-delayed-type’’ </em>to whatever exchange type you desire i.e fanout, topic, etc.</p><h4>Publishing messages</h4><p>Once the delay exchange has been declared, we can publish messages we intend to delay to it. To specify the duration of the delay, we add a property in the headers of the message called <em>“x-delay”. </em>The value of <em>“x-delay” </em>should be an integer representing the number of milliseconds the message should be delayed by RabbitMQ.</p><h4>Example Code</h4><p>Here’s a sample code that logs a message to the console at a time specified by a user.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/02c8dcc8a644aa5f84533515d04732b9/href">https://medium.com/media/02c8dcc8a644aa5f84533515d04732b9/href</a></iframe><p>Ensure RABBITMQ_CONN_STRING is available in your current shell session by typing this command:</p><pre>$ export RABBITMQ_CONN_STRING=amqp://your-connection-string</pre><p>To schedule a message “HelloSunshine” to be posted on Sun Aug 22 2021 17:19:56. You can run the app like so:</p><pre>node app.js HelloSunshine 2021-08-22T17:19:56</pre><p>“HelloSunshine” should be printed to the console at exactly Sun Aug 22 2021 17:19:56.</p><p><strong>NOTE:</strong> For this sample program, the message is expected to be a single string without spaces.</p><h4>Conclusion</h4><p>I hope this article has been worth your time. If you enjoyed this article, please leave a clap, it makes me happy 😄. You can also reach me via <a href="https://www.linkedin.com/in/georgeben/">LinkedIn</a>, I would be excited to hear from you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2bd47b20c6eb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Kubernetes: For Humans]]></title>
            <link>https://medium.com/@msdcconnect/introduction-to-kubernetes-for-humans-7559fb286a67?source=rss-3df1975af924------2</link>
            <guid isPermaLink="false">https://medium.com/p/7559fb286a67</guid>
            <category><![CDATA[cloud-native]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[k8s]]></category>
            <dc:creator><![CDATA[George Benjamin]]></dc:creator>
            <pubDate>Mon, 09 Aug 2021 20:02:10 GMT</pubDate>
            <atom:updated>2021-08-09T20:02:10.269Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/509/1*IYj_aGt-hbgkvjBIWewEVw.jpeg" /></figure><p>Today, Kubernetes is one of the fastest-growing technologies. It is being adopted by many businesses, both small and large. But why is it so popular? Why does it seem like everyone is talking about it?</p><h4>Who should read this?</h4><p>There are already tonnes of learning resources about Kubernetes on the internet, so what’s the point of another? This article is solely written for people who do not have a background in engineering but would love to have an idea of Kubernetes and how it can impact their business. This includes founders, product managers, support team, sales, etc.</p><h4>Background</h4><p>Before we can understand Kubernetes, we need to discover the problem it was created to solve. To explain this, I would use the scenario of an e-commerce company.</p><p>After developing your next “billion-dollar” e-commerce website, the next step is making it available to the public for use, so you can start making sales and eventually profit. But how exactly is this done? To make your website available to the public, you need to put it on a server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PKm3Im7rH2twCdKreex4DA.png" /><figcaption>A server is just a computer</figcaption></figure><p>A server is just a computer that is connected to the public internet. When customers visit your website, the server is responsible for delivering the resources needed for displaying your website.</p><h4>The problem</h4><p>The problem is servers are quite expensive to purchase. So, to make your website available to the public, you need to spend a lot of money buying these computers. You also need to ensure an uninterrupted power supply because if your server goes off, your website would be inaccessible, which could make you lose a lot of money. You are also required to provide unlimited internet connectivity, employ staff to maintain the servers, and provide support when things go wrong.</p><p>Whew! That’s a lot of expenses. Many small companies and startups couldn&#39;t afford to provide all this infrastructure, we needed a better solution.</p><h4>Welcome to the Cloud</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XohKRMOWkCOsoXrTse7Mag.jpeg" /><figcaption>What comes to your mind when you hear “the cloud”?</figcaption></figure><p>In this case, the cloud has nothing to do with the fluffy stuff you see in the sky. “The cloud” is simply a fancy term for a myriad of computers located somewhere in the world that power various services used by people.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*uleoBhTFM66iwqlkYMaK6w.jpeg" /><figcaption>What “the cloud” actually is</figcaption></figure><p>Large corporations like Amazon, Google, and Microsoft decided to purchase large amounts of servers, housing them in places known as “data centres”. This infrastructure is then provided <strong>on-demand</strong> to small businesses and startups for a little fee. This made it possible for almost anyone to place their product on the internet.</p><h4><strong>Benefits of the cloud</strong></h4><ul><li>Reduced cost: Businesses no longer had to spend tens of thousands of dollars to acquire infrastructure for running their applications. With just a few bucks, you can provision your required infrastructure on-demand from a cloud provider e.g Amazon Web Services (AWS), Microsoft Azure, Google Cloud Platform (GCP)</li><li>Self Service: You can provision infrastructure as the need arises, without having to wait several days for a physical server to be bought and set up.</li><li>Elasticity: The cloud can enable you to automatically scale your infrastructure up or down to fit the system requirements or user load. For example, during the holidays, the number of people purchasing gifts online surges, hence you would need more infrastructure to handle the increased traffic. This can be handled automatically by utilizing the cloud.</li></ul><h4>Yet another problem!</h4><p>Since infrastructure can now be provisioned on-demand as a result of the cloud, every time new infrastructure is provisioned, an engineer would need to perform the necessary configurations, install your website on the new infrastructure, and ensure it works properly. This can be very cumbersome and many times, engineers make mistakes that can lead to the website being unavailable to customers for a certain period of time.</p><p>Several tools have been created to make this process less tedious, but they didn’t solve the problem. We needed a way to be able to run our apps/websites on any infrastructure with minimum or no setup. We needed a guarantee that our website would be able to run correctly on any infrastructure. In situations where we need to provision new infrastructure to handle increased traffic from customers, we want to make this as fast as possible. Time is money!</p><h4>Containers to the rescue!</h4><p>Containers were created to solve the problem we just discussed. Containers are used for packaging applications so they can run anywhere irrespective of the underlying infrastructure. A container comprises your application, along with all the dependencies it requires to work correctly. A nice analogy is a ready-to-eat meal — there’s no need to prep your cooking ingredients or cook, you just put it in a microwave and it’s ready to be eaten.</p><p>Containers guaranteed your website/application would run on any infrastructure easily. Several tools can be used for creating containers, a popular example is Docker.</p><p>Containers made developing and running applications so smooth! However, as the size of your application grows, the number of containers you would need to run increases. As the number of containers you run increases, it becomes almost impossible to manage them manually. Managing refers to starting the containers that run your app, ensure the containers are running and healthy, restarting containers that were terminated, etc.</p><h4>Finally Kubernetes!</h4><p>Kubernetes is a tool that manages your containers for you. It takes away the inefficiencies involved with managing containers manually.</p><blockquote><a href="https://kubernetes.io/docs/concepts/overview/what-is-kubernetes/">Kubernetes</a>, also known as K8s, is an open-source system for automating deployment, scaling, and management of containerized applications. — <a href="https://kubernetes.io/">The official kubernetes website</a></blockquote><p>Now you get it!😄 Kubernetes is also referred to as a container orchestration tool. It schedules containers that should run, monitors their health, replaces unhealthy or terminated containers, and much more!</p><h4>Conclusion</h4><p>This idea of creating applications that leverage the unique benefits provided by the cloud is sometimes referred to as “Cloud native”. You might ask, so how does all this affect my business? How does it affect the failure or success of my start-up?</p><p>A key factor to the success of any business is speed. Customers love businesses that handle their needs quickly. The needs of customers are constantly changing. Organizations need to move faster to respond to customer needs so they can gain more profit. As the popular saying goes, you snooze, you lose! Cloud native helps businesses deliver new solutions faster, innovate faster, and offer reliable services their customers would love!</p><p>If you enjoyed reading this article, please share it with your team. You can reach me via my <a href="https://www.linkedin.com/in/georgeben/">Linkedin</a>, I would be thrilled to hear from you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7559fb286a67" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding modules in Node.js — The hidden parts]]></title>
            <link>https://medium.com/@msdcconnect/understanding-modules-in-node-js-the-hidden-parts-be62e93efaba?source=rss-3df1975af924------2</link>
            <guid isPermaLink="false">https://medium.com/p/be62e93efaba</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[modules]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[George Benjamin]]></dc:creator>
            <pubDate>Tue, 25 Dec 2018 21:21:35 GMT</pubDate>
            <atom:updated>2018-12-25T21:21:35.742Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*likAe6inl6ach2D-2jggTQ.jpeg" /><figcaption>How would npm packages taste if they were meals? Photo by <a href="https://unsplash.com/photos/iAZF6Gp4qLQ?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">rawpixel</a> on <a href="https://unsplash.com/search/photos/meal?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>If you’re confused about the difference between exports and module.exports and when to use the them, this article was specially written for you. 😉</p><h4>What are modules in node.js?</h4><p>Modules are simply files that contain code which can be used in your node application. For example, if you create a file called hello.js which contains the following code:</p><pre>console.log(&quot;Hello people!&quot;)</pre><p>You just created a module! That was easy right? But what really happens when I create a module? What happens when I execute the code written in a module? What happens when I include a module I wrote into another piece of code?</p><h4>What happens when I execute a module in Node.js?</h4><p>In the hello.js file you created (If you didn&#39;t create one, you could do so now), add the following line of code:</p><pre>console.log(arguments)</pre><p>According to MDN</p><blockquote>arguments is an Array-like object accessible inside <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions">functions</a> that contains the values of the arguments passed to that function.</blockquote><p>To execute the code you wrote above, open up your terminal, navigate to the directory the the file you just created is located, then type in the command: node hello.js (if you named your file differently, replace hello.js with the name of your file.</p><p>Quick question, what do you think the output would be?</p><p>After running our program, we have the following output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*YKCQ_cri_wbgF_p9aWaR3A.png" /></figure><h4>What happened?</h4><p>Behind the scene, node wraps the code written in the hello.js file into a function, then node also passes five arguments into this hidden function namely:</p><ul><li>exports — This object contains part of our code that can be exposed to other node programs.</li><li>module — This represents the current module.</li><li>require — Used to include other modules into your current module.</li><li>__filename — The path of the node.js file.</li><li>__dirname — The path to the folder containing our node.js file.</li></ul><p>So, we can say that a module in node.js is a function that receives arguments and returns a value. We are able to use keywords like exports, module and require, because they were passed as arguments to this hidden function node created when we executed our program.</p><h4>Exports vs module.exports, whats the difference?</h4><p>By default, the hidden function created by node returns something, which is the module.exports property. Therefore, whatever we set our module.exports property to will be returned by the hidden function, hence exposing it to other programs. The exports keyword only points to the module.exports property. Right now, our module doesn’t export anything, to export a part of your module to other programs, add the following line of code above the line where we console.log our arguments:</p><pre>exports.name = &quot;James Bond&quot;;<br>console.log(arguments);</pre><p>Executing the program again would give the following output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*aPUBh-JA1K3rPYMOjtfpdw.png" /></figure><p>Now we can see our exports argument contains a property; name which has the value “James Bond”. What this means is that any other program that includes our module using the require keyword, would have access to our name property.</p><p>The program above could as well be written as:</p><pre>module.exports.name = &quot;James Bond&quot;;<br>console.log(arguments);</pre><p>Running it again would give us the exact same result as we had earlier.</p><h4>When should I use exports and when should I use module.exports?</h4><p>If you want to expose a simple object to other programs, then its fine to use the exports keyword. For example, if I wanted to expose information about a user I could do it like so:</p><pre>exports.name = &quot;James Bond&quot;;</pre><pre>exports.job = &quot;Accountant&quot;;</pre><pre>exports.age = 21;</pre><p>If I wanted to use the module above in another file called app.js, I could do it like so:</p><pre>//app.js<br>const user = require(&#39;path to the module you want to include&#39;);<br>console.log(user.name) //Which outputs James Bond</pre><p>However if you want your module to expose only a string or a function to other programs, we could do it like so:</p><pre>module.exports = &quot;Hey! I&#39;m exported!&quot;;</pre><p>Then, we can include it in our app.js file like so:</p><pre>const myString = require(&#39;path to the module you want to include&#39;);<br>console.log(myString); //Displays &quot;Hey! I&#39;m exported!&quot;</pre><p>If it were to be a function, we could do something similar. Here, I want to expose a function that greets a person by the name passed to it as an argument:</p><pre>module.exports = name =&gt; console.log(`Hello ${name}! Nice to meet you.`) //I am using the ES6 arrow functions and template strings.</pre><p>Then we can include it in our app.js file like so:</p><pre>const myFunction = require(&#39;path to the module you want to include&#39;);<br>myFunction(&quot;James Bond&quot;) //Outputs Hello James Bond! Nice to meet you!</pre><p>So you might be thinking, what if I just set the exports object to what ever I want to expose like so:</p><pre>exports = &quot;Hey! I am exposed!&quot;</pre><p>We can include it in out app.js file like we did before:</p><pre>const myString = require(&#39;path to the module you want to include&#39;);<br>console.log(myString);</pre><p>When we execute app.js, we don’t see “Hey I’m exposed”, instead we get an empty object! This is because, exports is just a reference to the module.exports property, therefore when we set it to something else(the string “Hey! I’m exposed” in this case), we are no longer referencing the module.exports property but merely pointing to a string.</p><p>I hope you now understand what a module in node is and how we can use modules. Most of what was discussed in this tutorial was explained in this <a href="https://www.pluralsight.com/courses/nodejs-getting-started">Node.js course</a> by Samer Buna. If you learnt something or liked this article, please give it a clap. You could also follow me on <a href="https://twitter.com/BenGtheonly">Twitter</a>. Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be62e93efaba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unit Testing Your Java Code with JUnit — For the Confused.]]></title>
            <link>https://medium.com/@msdcconnect/unit-testing-your-java-code-with-junit-for-the-confused-81e5183f9249?source=rss-3df1975af924------2</link>
            <guid isPermaLink="false">https://medium.com/p/81e5183f9249</guid>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[tdd]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[junit]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[George Benjamin]]></dc:creator>
            <pubDate>Fri, 09 Nov 2018 21:15:21 GMT</pubDate>
            <atom:updated>2018-11-09T21:15:21.284Z</atom:updated>
            <content:encoded><![CDATA[<h3>Unit Testing Your Java Code with JUnit — For the Confused.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*NA2RQtLRd8XNbxqcTokRGQ.jpeg" /></figure><p>Hello, this is my very first article on medium and I’m excited to be writing about JUnit. As a java developer, there comes a time in your career where you’d be required to unit test your code, this article is aimed at guiding you through that phase in the easiest way possible. I was once totally confused about JUnit, but after I understood it, I found out it was as easy as A B C. So keep calm, smile and enjoy the ride.</p><h4>Who should read this?</h4><p>This article is meant for java developers who are new to JUnit or are confused on how to get started with JUnit.</p><h4>What is Unit Testing?</h4><p>I found a cool definition of Unit testing <a href="http://softwaretestingfundamentals.com/">here</a></p><blockquote><strong>UNIT TESTING</strong> is a level of software testing where individual units/ components of a software are tested. The purpose is to validate that each unit of the software performs as designed.</blockquote><p>Explanatory right? Let me explain a little more. When building a software, no matter how huge, that software would be made up of Java classes right? Just as the cell is the basic unit of an organism, a class is the basic unit of a java program. Unit testing involves testing all individual classes in a java program to ensure they perform as expected.</p><h4>Benefits of Unit Testing?</h4><p>Unit testing gives you assurance that your code works properly. Unit testing also allows you to discover bugs as they appear, because bugs will result in a failing test. There are many other benefits of unit testing which I won’t mention. That been said, let’s discuss about JUnit.</p><h4>What is JUnit?</h4><p>JUnit is a unit testing framework for the java programming language. You can read more about it <a href="https://junit.org/junit4/">here</a>.</p><h4>Okay! Let’s write some code!</h4><p>I would be using the Eclipse IDE for this tutorial, but you can use any IDE you prefer.</p><ol><li>Create a new java project, I’d be calling mine Dog. Yeah, just Dog.</li><li>Create a new java class and call it Dog.java. Copy and paste the following code into the newly created java class. We would be writing tests for this class.</li></ol><pre>public class Dog {</pre><pre>    private String mDogName;</pre><pre>    private String mDogBreed;</pre><pre>    private int mDogAge;</pre><pre>    private int mDogWeight;</pre><pre>    private boolean mDogIsHappy;</pre><pre>    public Dog(String name, String breed){</pre><pre>        this.mDogName = name;</pre><pre>        this.mDogBreed = breed;</pre><pre>        this.mDogWeight = 5;<br>    }</pre><pre>    public String getName(){</pre><pre>        return mDogName;</pre><pre>    }</pre><pre>    public void setName(String name){</pre><pre>        mDogName = name;</pre><pre>    }</pre><pre>    public int getWeight(){</pre><pre>        return mDogWeight;</pre><pre>    }</pre><pre>    public void setWeight(int weight){</pre><pre>        mDogWeight = weight;</pre><pre>    }</pre><pre>    public void eat(){</pre><pre>        System.out.println(&quot;Yuum that was delicious&quot;);</pre><pre>        mDogWeight += 5;</pre><pre>    }<br>    public void play(){</pre><pre>        mDogIsHappy = true;</pre><pre>    }</pre><pre>}</pre><p>The code above is a simple java class to create dogs, cool right?</p><p>Now, we will use JUnit 4 to test our Dog class and ensure all the methods are functioning properly.</p><p>3. Create a new java project in the same directory as the initial project and call it DogTest. Just add “Test” at the end of the project name to show that it contains the tests to our program.</p><p>4. Link the DogTest project to our Dog project. On Eclipse, right click on the DogTest folder, select the Build path option, then select the Configure Build path option. Make sure the Projects tab is selected, then click on Add. Select the Dog project and click OK.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*T4KqkqWdB_wW1lJMv6JSxg.png" /></figure><p>5. Now that the two projects are linked, we create our first test case! Right click on the Test project, then select New &gt; JUnit Test Case. Name the Test case DogTest, then click on O.K. Eclipse would generate some boilerplate code for us.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/1*hB1Ur1u7fg3UUqX68bg6KQ.png" /><figcaption>Empty test case</figcaption></figure><p>To run your test, right click anywhere on the code editor and select Run As &gt; JUnit Test. If you did everything correctly, your test should run!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*qfWyly3G_60Wqa0MvV1PFw.png" /><figcaption>The red bar indicates that our tests ran but failed.</figcaption></figure><p>Never mind that our test fails, we’d be fixing that next.</p><h4>JUnit Annotations</h4><p>JUnit annotations are used to control how our tests run. JUnit annotations give instructions to the JUnit test runner on how to run our tests. The basic Junit annotations are :</p><pre>@Test, @Before, @After, @BeforeClass, @AfterClass, @Ignore, @Test(expected = Exception.class)</pre><p>To create a JUnit test, we use the @Test annotation, then create a public method with returns nothing. The @Test annotation tells the JUnit test runner that the method below it is a JUnit test.</p><p>Lets create a Test to ensure that a dog is correctly being created. To create a dog, we pass in the name of the dog and it’s breed to the dog constructor. After creating a dog, we want to ensure that the name of the dog we created matches the name we passed in. So, how do we check that the result we expect is the same as the result we get from our method? We use the Assert class. The Assert class has a lot of methods to check if the results of our program match our expectations. Some common methods are : assertEquals, assertSame, assertFalse, assertNull. These are just a few methods from the Assert class.</p><p>Copy and paste the following code into the DogTest class.</p><pre>import static org.junit.Assert.*;</pre><pre>import org.junit.Test;</pre><pre>import com.georgeben.junittestingexample.Dog;</pre><pre>public class DogTest {</pre><pre>    @Test</pre><pre>    public void createNewDog(){</pre><pre>        Dog myDog = new Dog(&quot;Jimmy&quot;, &quot;Beagle&quot;);</pre><pre>        assertEquals(&quot;Error in creating a dog&quot;, &quot;Jimmy&quot;,    myDog.getName());</pre><pre>    }</pre><pre>}</pre><p>The assertEquals method takes three parameters. The first parameter is the message you want displayed if the test fails, which is optional. The second parameter is the expected value, the third is the actual value. From the code above, we created a new dog with the name Jimmy. Then, we check if the name of the dog we just created was “Jimmy” using the assertEquals method. We expect the name of the dog to be “Jimmy” and we get the actual name of the dog by calling the getName method of the dog. Now, lets run this test.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CUcktrn3YK0sunWlVCUxBg.png" /><figcaption>The green bar shows our tests passed.</figcaption></figure><p>Hurray! Our tests passed. If the name returned by the getName method was different from the name passed in as the expected parameter, the test would fail. That was easy right? Lets create another test to ensure that our eat() method is working properly. Copy and paste this line of code:</p><pre>@Test</pre><pre>public void feedDog(){</pre><pre>    Dog myDog = new Dog(&quot;Jimmy&quot;, &quot;Beagle&quot;);</pre><pre>    myDog.eat();</pre><pre>    assertEquals(&quot;Error when eating&quot;, 10, myDog.getWeight());</pre><pre>}</pre><p>As expected, all our tests pass. From the above code, we notice that we have duplicate lines in our test methods i.e we are always instantiating a new dog in each test method. Fortunately, JUnit has annotations we can use to specify the actions we need to perform before each of our test runs and after they run. The @Before annotation executes the specified code before each test is run, while the @After annotation executes the specified code after each test is run.</p><p>Let’s rewrite our DogTest class to include the @Before and @Afterannotation.</p><p>Note: The code that runs before is normally called setUp() while the code that runs after is called tearDown(), but you can call it anything you want.</p><pre>public class DogTest {</pre><pre>    Dog myDog;</pre><pre>    @Before</pre><pre>    public void setUp(){</pre><pre>        System.out.println(&quot;This is run before&quot;);</pre><pre>        myDog = new Dog(&quot;Jimmy&quot;, &quot;Beagle&quot;);</pre><pre>    }</pre><pre>    @After</pre><pre>    public void tearDown(){</pre><pre>        System.out.println(&quot;This is run after&quot;);</pre><pre>    }</pre><pre>    @Test</pre><pre>    public void createNewDog(){</pre><pre>        assertEquals(&quot;Error in creating a dog&quot;, &quot;Jimmy&quot;, myDog.getName());</pre><pre>    }</pre><pre>    @Test</pre><pre>    public void feedDog(){</pre><pre>        myDog.setWeight(5);</pre><pre>        myDog.eat();</pre><pre>        assertEquals(&quot;Error when eating&quot;, 10, myDog.getWeight());</pre><pre>    }</pre><pre>}</pre><p>After running the tests, your console should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*uzz7aWSCH2aXN6yL-lB8pA.png" /></figure><p>The @BeforeClassannotation is used to specify code that should be executed before any test runs, while the @AfterClass annotation specified code to be executed after all the tests are run, used mostly to clear up system resources.</p><p>You see? Writing unit tests with JUnit is not as hard as it seems. To learn how to use the other annotations in JUnit, checkout the completed example on github by clicking <a href="https://github.com/georgeben/JUnit-Unit-Testing-Example">here</a>.</p><p>Thanks for your time. I hope you learnt something. You can kindly follow me for more exciting articles. Also follow me on <a href="https://twitter.com/BenGtheonly">Twitter</a>. Thanks once again.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=81e5183f9249" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>