Category Archives: Programming

Reflection on “Coding Standards and Guidelines”

by: Queenstar Kyere Gyamfi

The GeeksforGeeks article “Coding Standards and Guidelines” highlights the importance of writing code that is clean and consistent. It also underlines the need for code that is easy to understand. It explains that coding standards are a set of rules and conventions that help developers maintain clarity and quality across a project. These standards cover areas such as naming conventions, indentation, code structure, comments, and documentation. The article emphasizes that following standards is not about limiting creativity. It is about making sure that everyone working on a project can easily read and maintain the code. It also points out that coding guidelines help prevent errors. They make debugging easier. They ensure that software projects remain manageable as they grow.

I chose this resource because I’ve noticed how quickly group projects can become messy. Each person having a different coding style contributes to this messiness. I’ve always cared about writing code that works. I’ve started realizing that how the code looks and reads is just as important. This is especially true in team environments. This article stood out to me because it clearly explained the purpose behind coding standards.

One key lesson I learned from this article is that consistency builds trust among developers. When everyone follows the same structure, it becomes easier to understand, review, and modify code written by others. The article also reinforced the idea that good code should be self-explanatory. For example, meaningful variable names like totalPrice or userCount communicate intent better than short, unclear ones like x or val. I also learned how proper indentation and spacing make code more readable and reduce the risk of logic errors that come from misaligned statements or missing braces.

Reading this resource made me reflect on my own coding habits. Sometimes, when I’m rushing to finish an assignment, I skip comments or mix naming styles without thinking about how confusing it might be later. Now, I see that writing clean code is an investment as it saves time when debugging and helps others understand what I meant. I also want to use tools like linters and formatters to automatically enforce standards in my projects.

Overall, this article helped me understand that coding standards are not about perfection but they are about communication. Clean, organized code reflects professionalism and respect for the next person who will read it. It reminded me that in software process management, technical skills and teamwork go hand in hand. Writing code that others can easily follow is one of the best ways to contribute to a project’s long-term success.

LINK TO RESOURCE:

https://www.geeksforgeeks.org/software-engineering/coding-standards-and-guidelines/

From the blog CS@Worcester – Circuit Star | Tech & Business Insights by Queenstar Kyere Gyamfi and used with permission of the author. All other rights reserved by the author.

From Inheritance to Strategy: Lessons from the Duck Simulator

One of the primary obstacles in software design is ensuring that code remains easy to maintain and extend. Initially, inheritance seems like the clear answerplacing shared code in a superclass and allowing subclasses to override as necessary. However, as demonstrated in the classic Duck Simulator example, relying solely on inheritance can result in fragile designs.

From Inheritance to Strategy

In the first version of the Duck Simulator, all ducks derived from a base Duck class. This approach worked until we introduced unique ducks like RubberDuck (which squeaks instead of quacking and cannot fly) and DecoyDuck (which does neither). Suddenly, we found ourselves needing to override or disable inherited methods, leading to duplication and design issues such as viscosity and fragility. Transitioning to interfaces helped to declutter the design, but it also required us to replicate code across similar ducks. The true breakthrough arrived with the Strategy Pattern,

We extracted behaviors like flying and quacking into separate classes (FlyWithWings, FlyNoWay, Quack, Squeak, MuteQuack). Now, ducks possess behaviors rather than inheriting them. These behaviors can be altered at runtime, and new ones can be introduced without changing existing code. This transition underscored the principle of favoring composition over inheritance and illustrated the Open-Closed Principle: code is open for extension but closed for modification.

Design Principles in Action

The exercise reinforced several essential principles: High Cohesion: Each behavior class excels at a single task. Low Coupling: Ducks are indifferent to how they fly or quack, only that they can delegate to a behavior. Encapsulate What Varies: Changes in behavior are contained, not dispersed across subclasses. Collectively, these factors enhance the design’s flexibility and maintainability.

UML: Clearly Communicating Design

We also engaged in the practice of illustrating designs through UML diagrams. In contrast to code, UML offers a higher-level representation that clarifies relationships: Associations (for instance, a Student possessing a schedule of Course objects). Multiplicity (for example, a student may enroll in 0–6 courses). Inheritance and interfaces (such as Faculty extending Employee and implementing HasCourseSchedule). Tools like PlantUML enable us to create these diagrams in Markdown, facilitating easy adjustments and sharing.

Key Takeaways

Relying solely on inheritance frequently results in fragile designs. The Strategy Pattern addresses this issue by encapsulating behavior and employing composition. Guiding principles such as High Cohesion, Low Coupling, and Open-Closed promote cleaner designs. UML diagrams provide us with a common language to convey and analyze code. What began as a straightforward duck simulator evolved into an insightful lesson on the significance of design patterns. By embracing the Strategy Pattern and utilizing UML for design modeling, we discovered how to construct systems that are not only functional but also resilient, adaptable, and easy to maintain.

From the blog CS@Worcester – MY_BLOG_ by Serah Matovu and used with permission of the author. All other rights reserved by the author.

Blog 1 Version Control

 Version Control in Software Process Management 

I am Dipesh Bhatta, and I am writing this blog entry for CS-348 Software Process Management for Blog Quarter 1. I chose to write about version control and how it is applied in software process management. My chosen resource is an article entitled “What is Version Control?” by Atlassian’s Git tutorials ( https://www.atlassian.com/git/tutorials/what-is-version-control ). This passage explains what version control is, why software projects require it, and how developers use it in practice. 

The passage defines version control as a process that records file changes over time. It allows several people to work on the same project simultaneously without losing work or overwriting each other’s work. Another important advantage is that version control has a complete history of the project, and developers can go back to an earlier version or reverse mistakes when necessary. The article also explains how the older systems, like the centralized ones such as Subversion (SVN), differ from newer distributed systems such as Git. Git has risen to be the most widely used version control system because it offers each developer a full copy of the project; thus, it is reliable and flexible. Apart from this, the article captures the workflows like branching, merging, and pull requests, which make collaboration safer and more structured. 

I used this resource because version control is associated with managing the software process, the subject of CS-348. The course is all about managing software development in an organized fashion, and version control is one of the most important tools used to facilitate this process. I also wanted to understand the reason why version control is crucial and not just how to use it, since understanding its purpose makes me aware of its application in professional software development. 

This article made me realize version control is not just saving code—it is a process of keeping collaboration and advancement. Without it, projects quickly become unmanageable, and you can’t even know who did what to the code. The explanation of Git branches was most helpful because it mirrors what we do in CS-348. Branches allow developers to experiment with new functionality without affecting the original codebase, and this is a clear demonstration of process management in action. 

The article also got me to think about my own working habits. Writing good commitment messages, responsible use of branches, and adherence to a process-based workflow are all habits that enhance collaboration and project quality. These habits will benefit me in group projects from now on and later in professional work. 

In short, version control is an essential part of software process management. It facilitates collaboration, organization, and accountability—all major themes in CS-348. By performing these routines throughout Blog Quarter 1, I am creating technical skills as well as professional routines that will benefit me throughout my career. 

From the blog CS@Worcester – dipeshbhattaprofile by Dipesh Bhatta and used with permission of the author. All other rights reserved by the author.

Understanding Git Collaboration: Communities, Upstreaming, and Merge Conflicts

Hello everyone! Welcome back to my blog posts. Today I would be delivering my first Quarter blog post.

For this week’s blog, I decided to read “Git Forks and Upstreams: How-to and a cool tip” from Atlassian Git Tutorials. I picked this article because it connects directly with what we’ve been practicing in class—working locally, pushing changes upstream, staying synchronized, and handling merge conflicts. I also wanted a guide that explained the actual Git commands rather than just high-level concepts, since I’ve been moving away from relying only on graphical interfaces.

Summary of the Resource

The article explains the difference between origin (your fork) and upstream (the original repository you forked from). It walks through how to set up your fork so you can keep it synchronized with the upstream repo, which is especially important when multiple people are contributing. Commands like git remote add upstream <url>, git fetch upstream, and git merge upstream/main are introduced step by step. The tutorial also shares a useful tip for checking how many commits your branch is ahead or behind the upstream, which makes it easier to stay in sync.

Why I Chose This Resource

I chose this article because it fills a gap in my own Git knowledge. Until recently, I mainly used the graphical interface on the side to commit, push, and sync my changes. That worked for basic assignments, but I often felt like I didn’t really understand what was happening behind the scenes. This tutorial helped me connect the dots by showing me the exact commands and explaining why they matter, especially in collaborative projects.

Reflection and Takeaways

This resource helped me see Git as more than just a tool for saving code. it’s really about teamwork. Understanding how to add and pull from upstream makes me feel much more prepared to collaborate on group projects or open-source contributions. I no longer see merge conflicts as something to fear, but as a natural part of multiple people working on the same code.

One big realization for me was how important it is to stay synchronized with upstream. In one project I did before, I once ignored updates for too long, and the merge that followed was messy and stressful. Now I understand that frequent git fetch upstream and git merge calls prevent bigger problems down the road.

Another personal shift was moving away from the GUI. While the interface made Git feel easier at first, I see now that the terminal gives me more power and clarity. Running git status, git log, or checking how far ahead/behind my branch is compared to upstream makes me feel more in control. It’s like going from driving an automatic car to learning manual, I finally understand how things actually work under the hood.

Looking ahead, I know these lessons will help me not only in this class but also in internships and my future career. Whether I’m working on an open-source project or contributing to a company’s codebase, being comfortable with upstream workflows and conflict resolution will make me a stronger and more reliable teammate.


Citation / Link

From the blog CS@Worcester – Rick’s Software Journal by RickDjouwe1 and used with permission of the author. All other rights reserved by the author.

Welcome to My Journey in CS 343: Software Construction, Design & Architecture

Hello everyone, my name is Rick Djouwe, and this semester I am beginning CS 343: Software Construction, Design & Architecture. I am truly excited for this class because it represents the next step in strengthening my ability to think beyond coding and focus on building well-structured, scalable, and maintainable software systems.

What This Course is About

CS 343 covers a wide range of essential topics in modern software development, including:

  • Design principles such as abstraction, encapsulation, inheritance, and polymorphism.
  • Best practices like SOLID, DRY (“Don’t Repeat Yourself”), and YAGNI (“You Ain’t Gonna Need It”).
  • Design patterns that provide reusable solutions to common problems.
  • Software architectures and frameworks, including REST API design.
  • Refactoring, code smells, and concurrency, which improve software quality and longevity.
  • Modeling and documentation tools like UML, which ensure clear communication of design decisions.

In short, this course is not just about writing code, it’s about learning to think like a software engineer who can approach problems critically, design solutions thoughtfully, and work effectively with others.

Skills and Outcomes

Through CS 343, I will gain valuable experience in:

  • Collaborating with stakeholders to design, test, and deliver software systems.
  • Applying professional judgment and staying current with evolving tools and practices.
  • Organizing projects using proven methodologies and team processes.
  • Communicating complex technical concepts clearly, both in writing and orally.

These outcomes connect directly to the broader goals of my Computer Science major: analyzing problems, building solutions, and developing the professional skills needed to succeed in the field.

Why This Matters to Me

As someone pursuing a career as a software engineer specializing in artificial intelligence, this course will help me strengthen the foundations of software design and architecture that are critical in building intelligent, scalable systems. Beyond my academic goals, I also see a strong connection to my current role as an Automation Developer at The Hanover Insurance Group, where I contribute to projects that rely on thoughtful design, testing, and collaboration. The principles and practices I learn here will make me more effective in my work today while preparing me for even greater responsibilities in the future.

I am eager to reflect on my progress throughout the semester, connect this material with experiences across my other courses, and apply these lessons directly to both my professional role and long-term career.

For me, CS 343 is more than a class, it’s a bridge between where I am now and the kind of innovative, responsible, and skilled software engineer I strive to become. I am also excited to meet everyone in this course and learn from each other as we move forward together. Feel free to reach out if you’d like to connect, collaborate, or study together this semester!

From the blog Rick’s Software Journal by RickDjouwe1 and used with permission of the author. All other rights reserved by the author.

Sprint 3 Retrospective The Final

Photo by Ollie Craig on Pexels.com

Debug Ducker here, now with my final Sprint retrospective for the semester. I want to not only reflect on the progress made on this sprint, but also the past sprints as well.

Initially, when starting the project, we had a different scope in mind than what was needed. Expiration dates aren’t what many think they mean. They are made by a company, there are no governing bodies that oversee expiration dates, and meant for markets to throw stuff out that isn’t fresh. So we decided to instead try to make it so that when a product is scanned, it will then display the USDA food guidelines on what to do to ensure the food is within the spoilage range. We then introduced what we had for our customer during Sprint 1, which at the time, we had the scanner system and the inventory backend. What we learn here is that the customer has an idea of what they want, while the programmers may have a different idea. The customer said that in the pantry, they remove food after 6 months, and realizing this decided to shift our development to just displaying if a product goes bad after six months, so the group worked on displaying how long a product in the inventory can go on for instead. I feel this is a great example of customer input that I learn, as they may have an idea that we can not change completely, but improve on through software, so instead of manually checking the food, they can just check in the database what products are past the six months. As a result, our final product reflects that

This last sprint was our tidying-up sprint. We just needed to tidy some code to make it cleaner and also fill out some documentation for the next group, which I was in charge of. The tidying code is where the issue lies. You see, we use a certain code as a base to work off from for smoother development. The problem is that a lot of the words and variables used are based on the previous code base, which was guest. Since this backend is meant for product, we wanted to replace every instance of guest with product so future developers won’t be confused like we were. Unfortunately, just finding and replacing all instances of guest was not going to be easy, as the problem was deeper than a few JavaScript files. It seems the issue lies deeper within the code, and it was an issue that would have taken too long to fix. I feel perhaps we could have avoided this issue at the start if we had gone out of our way to change the variable names in the beginning of the project. Though I am still not sure if that had fixed everything.

Before we end, I want to thank my team for being the best one I’ve had. I don’t think I’ll find an understanding and kind group like this even in my upcoming professional career. I’m going to graduate from college soon, a big change in my life with new responsibilities. Furthermore, I remember a pattern from the book “Apprenticeship Patterns”, by Dave Hoover and Adewale Oshineye. This book has been mentioned a lot in my retrospective, but a lot of what is said is thought-provoking. The most thought-provoking pattern to me is the Long Road. This pattern speaks about learning and growing your skills over a long period to be what is called a master software craftsman. You need to think in the long term, not short-term gains. I feel this will be important when it comes to my future in the software development field. It is going to be a long journey where I will gain new skills and abilities that will leave me unrecognizable from my previous self. Though this one will take time and an unknown amount of time that I am prepared to face. It will be a journey full of unexpected twists and turns, but it will be worth it in the end. I learned a lot from this group project and I hope to apply it in the future

Thank you for your time, Debug Ducker out.

Final results of the Backend in collaboration with me and 2 other devs

https://gitlab.com/LibreFoodPantry/client-solutions/theas-pantry/inventorysystem-culling/inventorybackend

Final results of the frontend scanner work

https://gitlab.com/LibreFoodPantry/client-solutions/theas-pantry/inventorysystem-culling/addbarcodefrontend

From the blog Debug Duck by debugducker and used with permission of the author. All other rights reserved by the author.

Sprint Retrospective: Learning to love Group Projects

Hi Debug Ducker here, and I just recently finished my first sprint with a group project. I have to say it went well, better than I expected. This coming from someone who has had poor experiences with group work.

Let’s begin on what exactly was working on for these past months. You see I was assigned to work on a project based on my college campus’s food pantry. We were assigned to work on an Inventory culling system based on the expiration dates of the products on the shelves. To say that I had way more different expectations of what needed to be done would be an understatement but I am getting ahead of myself.

Back to the main project, I am in a group of five and we came up with several ways to approach this project. We decided that we should split the work, two would work on a scanner that would check the items’ barcodes for identifying product information and the other 3 would work on the backend for the function of culling the inventory.

I found that working on separate parts of the project worked well in the long run allowing people to focus on one of the many aspects of the projects. Especially with the amount that got done at the end. I would know as my part of the project was going well….sorta. 

There was some trouble, such as using an already established code as the base for the project. It made me realize something, I wasn’t sure how to approach the issues as the code base was made with and due to my lack of knowledge of JavaScript, it was going to be problematic. Fortunately, I had 2 other companions that could assist me and did a great job. From this, I seek to improve my overall knowledge of JavaScript and seek ways to utilize the code base better.

Recently I read a bit of a programmer mentoring book called Apprenticeship Patterns by Dave Hoover and Adewale Oshineye. This experience reminds me of a pattern that I resonated with. Accurate Self-assessment, basically identifying what you know and what you don’t. A self-reflection of my skills and I found out that there is more that I can learn. I want to see this project succeed so I think I need to brush up on some skills that I am lacking so the project can come out great. That pattern is a good encouragement for me to study further.

Near the end of the project I was worried that it wasn’t going to be complete by our standards, fortunately, the other group got the scanner worker to find it, and we made some progress on the backend but I found that it didn’t reach our goal of what we wanted it to do. In the end, we were satisfied with our progress and hope to continue integrating the rest of the work.

Here is most of the work I have done it was mostly focused on trying to figure out testing our culling system and integration of product schema.

https://gitlab.com/LibreFoodPantry/client-solutions/theas-pantry/inventorysystem-culling/guestinfobackend/-/tree/main/specification?ref_type=heads

Here is the backend for the rest of the work done in collaboration with the others

https://gitlab.com/LibreFoodPantry/client-solutions/theas-pantry/inventorysystem-culling/guestinfobackend/-/tree/main/src?ref_type=heads

Thank you for your time, Have a nice one.

From the blog CS@Worcester – Debug Duck by debugducker and used with permission of the author. All other rights reserved by the author.

The Intersection of Manual Testing, Automated Testing, Equivalence Class Testing, and Security Testing

Hello guys, welcome to my second blog. In my previous blog, I explored JUnit testing, focusing on boundary value analysis and how to use assert Throws for exception handling in Java. Those concepts helped us understand how to write robust test cases and ensure that our software behaves correctly at its limits.

Building on that foundation, this post expands into a broader discussion of manual vs. automated testing, equivalence class testing, and security testing. These methodologies work together to create a comprehensive testing strategy that ensures software is functional, efficient, and secure.

Introduction

Software testing is a critical part of the software development lifecycle (SDLC). Among the various testing methodologies, manual testing, automated testing, equivalence class testing, and security testing play vital roles in ensuring software reliability, performance, and security. This article explores these techniques, their strengths, and how they work together.

Manual vs. Automated Testing

Testing software can be broadly categorized into manual testing and automated testing. Each approach serves specific purposes and has its advantages.

Manual Testing

Manual testing involves human testers executing test cases without automation tools. It is useful for exploratory testing, usability testing, and cases requiring human judgment.

Pros:

  • Suitable for UI/UX testing and exploratory testing
  • Requires no programming skills
  • Provides a human perspective on software quality

Cons:

  • Time-consuming and repetitive
  • Prone to human errors
  • Inefficient for large-scale projects

Automated Testing

Automated testing uses scripts and testing frameworks to execute test cases automatically. It is ideal for regression testing and performance testing.

Pros:

  • Faster execution and scalable for large projects
  • Reduces human errors
  • Works well with continuous integration/continuous deployment (CI/CD)

Cons:

  • High initial setup cost
  • Requires programming expertise
  • Not suitable for exploratory testing

Example: Java Automated Test Using Selenium

Here is a basic example of using Java to automate a test: I have a simple Calculator class and an Add method. There is a test that runs without human intervention once executed

public class Calculator {
    public int add(int a, int b) {
        return a + b;
    }
}

import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;

public class CalculatorTest {
    @Test
    public void testAddition() {
        Calculator calculator = new Calculator();
        int result = calculator.add(2, 3);
        assertEquals(5, result); 
    }
}

Equivalence Class Testing

Equivalence Class Testing (ECT) is a black-box testing technique that reduces the number of test cases while ensuring comprehensive test coverage. It divides input data into equivalence classes, where each class represents similar expected outcomes.

How It Works:

  • Identify input conditions
  • Categorize inputs into equivalence classes (valid and invalid)
  • Select one representative input from each class for testing

Example: Equivalence Class Testing in Java

Consider a function that validates age input:

public class AgeValidator {
    public static String validateAge(int age) {
        if (age >= 18 && age <= 60) {
            return "Valid Age";
        } else {
            return "Invalid Age";
        }
    }

    public static void main(String[] args) {
        System.out.println(validateAge(25)); // Valid input class
        System.out.println(validateAge(17)); // Invalid input class
        System.out.println(validateAge(61)); // Invalid input class
    }
}

Security Testing: A Critical Component

Security testing ensures that applications are protected against cyber threats. This is increasingly crucial with rising cyberattacks and data breaches.

Key Security Testing Techniques:

  • Penetration Testing: Simulating cyberattacks to identify vulnerabilities.
  • Static Code Analysis: Reviewing source code for potential security flaws.
  • Dynamic Analysis: Testing a running application for security weaknesses.
  • Fuzz Testing: Inputting random data to identify unexpected behavior.

Example: Basic SQL Injection Test

A common security vulnerability is SQL Injection. Here’s an example of a vulnerable and a secure implementation:

Vulnerable Code:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class SQLInjectionVulnerable {
    public static void getUserData(String userId) {
        try {
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "user", "password");
            Statement stmt = conn.createStatement();
            String query = "SELECT * FROM users WHERE id = " + userId; // Vulnerable to SQL Injection
            ResultSet rs = stmt.executeQuery(query);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Secure Code:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class SQLInjectionSecure {
    public static void getUserData(String userId) {
        try {
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "user", "password");
            String query = "SELECT * FROM users WHERE id = ?";
            PreparedStatement pstmt = conn.prepareStatement(query);
            pstmt.setString(1, userId);
            ResultSet rs = pstmt.executeQuery();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

How These Testing Methods Work Together

Each testing approach contributes uniquely to software quality:

  • Manual and automated testing ensure functional correctness and usability.
  • Equivalence class testing optimizes test case selection.
  • Security testing safeguards applications from threats.

By integrating these methods, development teams can achieve efficiency, reliability, and security in their software products.

Conclusion

A strong testing strategy incorporates manual testing, automated testing, equivalence class testing, and security testing. Leveraging these approaches ensures robust software quality while improving development efficiency.

For further exploration, consider:

From the blog Rick’s Software Journal by RickDjouwe1 and used with permission of the author. All other rights reserved by the author.

Effective Exception Testing in JUnit 5: Boundary Value Testing and AssertThrows

Introduction

In modern software development, ensuring that a program handles exceptions correctly is crucial for building robust applications. Exception testing in JUnit 5 allows developers to verify that their code properly handles error scenarios, improving reliability and maintainability. This blog post explores key techniques such as Testing for Exceptions in JUnit 5, Boundary Value Testing, and using AssertThrows to create effective test cases.

Testing for Exceptions in JUnit 5

JUnit 5 provides a streamlined way to test exceptions in Java applications. Unlike JUnit 4, which required using the expected attribute or @Rule, JUnit 5 introduces Assertions.assertThrows(), offering a more flexible and readable approach.

Example of Exception Testing in JUnit 5

Consider a method that calculates the square root of a number. If a negative number is provided, it should throw an IllegalArgumentException.

import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;

class MathUtilsTest {

    double calculateSquareRoot(double number) {
        if (number < 0) {
            throw new IllegalArgumentException("Number must be non-negative");
        }
        return Math.sqrt(number);
    }

    @Test
    void testCalculateSquareRootException() {
        IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> {
            calculateSquareRoot(-5);
        });
        assertEquals("Number must be non-negative", exception.getMessage());
    }
}

This test verifies that the method correctly throws an exception when given invalid input, ensuring robustness.

Boundary Value Testing

Boundary Value Testing (BVT) is a technique used to test the limits of input values. It focuses on edge cases, such as minimum and maximum values, where software is most likely to fail.

Example: Boundary Testing for Age Validation

Consider a function that validates a user’s age for registration, allowing only ages between 18 and 65.

boolean isValidAge(int age) {
    return age >= 18 && age <= 65;
}

Boundary tests should check values just inside and just outside the valid range:

import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;

class AgeValidatorTest {
    
    @Test
    void testAgeBoundaries() {
        assertTrue(isValidAge(18)); 
        assertTrue(isValidAge(65));  
        assertFalse(isValidAge(17)); 
        assertFalse(isValidAge(66)); 
    }
}

BVT ensures the system correctly distinguishes between valid and invalid inputs.

Testing for Exceptions with AssertThrows

The assertThrows method in JUnit 5 simplifies exception testing, making tests more readable and maintainable. It helps validate that methods correctly handle invalid inputs by throwing the expected exceptions.

Example: Division by Zero Handling

Consider a simple method that performs division:

int divide(int dividend, int divisor) {
    if (divisor == 0) {
        throw new ArithmeticException("Cannot divide by zero");
    }
    return dividend / divisor;
}

We can use assertThrows to verify proper exception handling:

import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;

class DivisionTest {

    @Test
    void testDivideByZero() {
        ArithmeticException exception = assertThrows(ArithmeticException.class, () -> {
            divide(10, 0);
        });
        assertEquals("Cannot divide by zero", exception.getMessage());
    }
}

This ensures that the division method correctly throws an exception when dividing by zero.

Conclusion

Testing exceptions effectively is a vital part of software quality assurance. JUnit 5’s assertThrows method, combined with Boundary Value Testing, enables developers to create thorough test cases that improve the reliability and robustness of applications. By writing well-structured exception tests, developers can prevent unexpected failures and ensure their applications behave as expected under various conditions.

For further reading, check out:

#JUnit5 #ExceptionTesting #AssertThrows #BoundaryValueTesting

From the blog Rick’s Software Journal by RickDjouwe1 and used with permission of the author. All other rights reserved by the author.

Week 0 – Set Up Task 5

Been a hot second since I wrote here, but nonetheless, I’m happy to be back. This week I’ll be taking a look at the project I will be working on all this semester for CS-448, LibreFoodPantry and Thea’s Pantry.

Professor Wurst wanted us to take a look at each project, and find things we found interesting about each. Starting with LibreFoodPantry, I actually chose their Mission statement, because it gave me a lot more insight into this project then I initially had. I had assumed it was specifically a project Worcester State was doing for Thea’s Pantry, but no. It’s actually a project that spans across multiple college campuses, which I found to be very interesting. I am curious to see if this year we will be working with any other colleges also working for LibreFoodPantry.

As for Thea’s Pantry, I chose the Technology tab, because I was curious as to the technology we were using. In specific, I was surprised to find we were working with GitLab again this semester. I have known for awhile now that the industry standard for repositories in GitHub, so I’m interested to learn and know exactly why we are using GitLab over it. I also am happy to see we will be utilizing Docker and MongoDB from previous courses with Professor Wurst.

Overall, looking into these documentation, I am excited to be working on these projects for my Capstone. Here’s to another semester at Worcester State with Professor Wurst!

From the blog CS@Worcester – You&#039;re Telling Me A Shrimp Wrote This Code?! by tempurashrimple and used with permission of the author. All other rights reserved by the author.