Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
JUnit - Inventory Stock Testing as a Maven Project
Next article icon

JUnit - Inventory Stock Testing as a Maven Project

Last Updated : 31 Aug, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

The quality of the software is very important. Though Unit tests and integration tests are done in the manual testing way, we cannot expect all kinds of scenarios to test. Hence as a testing mechanism, we can test a software code or project by means of JUnit. In this article let us see how to do testing for inventory stock by using JUnit. Via a Maven project, let us see the project concept 

Project Structure:

 

Let us see the dependencies of this project via

pom.xml

XML
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0"          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0                              http://maven.apache.org/xsd/maven-4.0.0.xsd">      <modelVersion>4.0.0</modelVersion>     <groupId>com.gfg.stock</groupId>     <artifactId>StockService</artifactId>     <packaging>jar</packaging>     <version>1.0-SNAPSHOT</version>      <properties>         <!-- https://maven.apache.org/general.html#encoding-warning -->         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>         <maven.compiler.source>1.8</maven.compiler.source>         <maven.compiler.target>1.8</maven.compiler.target>         <junit.version>5.3.1</junit.version>         <pitest.version>1.4.3</pitest.version>     </properties>      <dependencies>          <!-- junit 5, unit test -->         <!-- This is the much desired dependency and then only we can do testing -->         <dependency>             <groupId>org.junit.jupiter</groupId>             <artifactId>junit-jupiter-engine</artifactId>             <version>${junit.version}</version>             <scope>test</scope>         </dependency>      </dependencies>     <build>         <finalName>maven-mutation-testing</finalName>         <plugins>             <plugin>                 <groupId>org.apache.maven.plugins</groupId>                 <artifactId>maven-surefire-plugin</artifactId>                 <version>3.0.0-M1</version>             </plugin>              <plugin>                 <groupId>org.pitest</groupId>                 <artifactId>pitest-maven</artifactId>                 <version>${pitest.version}</version>                  <executions>                     <execution>                         <id>pit-report</id>                         <phase>test</phase>                         <goals>                             <goal>mutationCoverage</goal>                         </goals>                     </execution>                 </executions>                  <!-- https://github.com/hcoles/pitest/issues/284 -->                 <!-- Need this to support JUnit 5 -->                 <dependencies>                     <dependency>                         <groupId>org.pitest</groupId>                         <artifactId>pitest-junit5-plugin</artifactId>                         <version>0.8</version>                     </dependency>                 </dependencies>                 <configuration>                     <targetClasses>                         <param>com.gfg.stock.*Stock*</param>                     </targetClasses>                     <targetTests>                         <param>com.gfg.stock.*</param>                     </targetTests>                 </configuration>             </plugin>          </plugins>     </build>  </project> 

Let us see the business logic file

StockService.java

Java
public class StockService {     // instance variable     private int qtyOnHand;          // Parameterized constructor used to      // initialize the value of qtyOnHand     public StockService(int qtyOnHand) {         this.qtyOnHand = qtyOnHand;     }        // While adding stock items, we have to      // check whether is it positive or not     private void isValidQty(int quantity) {         if (quantity < 0) {             throw new IllegalArgumentException("Given stock quantity should be positive!");         }     }            // While adding the stock, we have to check whether      // input quantity is positive     // and if so, it will get added with the existing stock     public int addTheStock(int qty) {         isValidQty(qty);         qtyOnHand = qtyOnHand + qty;         return qtyOnHand;      }           // While deducting the stock, we have to check      // whether input quantity is positive     // and if so, we need to check are we deducting the     // stock with the available quantity     // Eg : if there are 100 quantities available, only     // that 100 quantity can be deducted     // If we pass 101 items to get deducted, logivally it is wrong     public int deductTheStock(int qty) {          isValidQty(qty);          int newQty = qtyOnHand - qty;         if (newQty < 0) {             throw new IllegalArgumentException("Out of Stock!");         } else {             qtyOnHand = newQty;         }         return qtyOnHand;      }  } 

Now we need to see the test file that can help for automated testing via JUnit

TestStockService.java

Java
package com.gfg.stock;  import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test;  public class TestStockService {      @DisplayName("Test deduct stock")     @Test     public void testDeductTheStock() {         // Initializing the stock to have 100 quantities         StockService obj = new StockService(100);                // If we remove 10 stocks, the expected         // result is 90-> (100 - 10)              assertEquals(90, obj.deductTheStock(10));                 // If we remove 90 stocks, the expected result is 0         assertEquals(0, obj.deductTheStock(90));         assertEquals(0, obj.deductTheStock(0));          Assertions.assertThrows(IllegalArgumentException.class, () -> {             obj.deductTheStock(-1);         });                  // As while reaching this point, we do not have any          // stock because of previous deductions         // hence stock has gone to negative value         // and hence this is correct         Assertions.assertThrows(IllegalArgumentException.class, () -> {             obj.deductTheStock(100);         });      }      @DisplayName("Test add stock")     @Test     public void testAddTheStock() {         // Initializing the stock to have 100 quantities         StockService obj = new StockService(100);                   // If we add 10 more stocks, the expected result is 110         assertEquals(110, obj.addTheStock(10));         assertEquals(110, obj.addTheStock(0));                  // Need to show errors when negative quantity is added         Assertions.assertThrows(IllegalArgumentException.class, () -> {             obj.addTheStock(-1);         });     }   } 

Let us test the scenarios by using the JUNIT Testcase execution

 

Output:

JUnit Result
 

In case the business logic is written wrongly or the way of comparing the values is wrong, then we will end up with errors let us see one such scenario

Java
@Test public void testDeductTheStock() {         StockService obj = new StockService(100);         // Here after deduction of 10 quantities, result will become 90         // But while testing, it has been provided with 100, which is wrong         assertEquals(100, obj.deductTheStock(10));       //....   } 
Junit Error
 

Conclusion

JUnit is very helpful to find the errors. Manual testing will lead to human errors because we cannot predict all the scenarios. Hence nowadays to qualify a software product, mandatorily one has to check them with JUnit.


Next Article
JUnit - Inventory Stock Testing as a Maven Project

P

priyarajtt
Improve
Article Tags :
  • Java
  • Software Testing
  • JUnit
Practice Tags :
  • Java

Similar Reads

    JUnit - Testcases for Credit Card Validation as a Maven Project
    In this article let us see a much-required functionality that is credit card validation as well as its relevant JUnit test cases for given credit card numbers. In an e-commerce project, credit card payment is the valid and much desired required functionality. We need to have a proper validation mech
    6 min read
    JUnit Testing For MySQL Project in Java
    For testing a software project, automated testing is always good and that will produce error-prone results. In the case of manual testing, there are possibilities of human errors. In this article let us take a sample project and let us see how to write JUnit test cases for it. Example Project Projec
    6 min read
    How to Test a Maven Project using EasyMock?
    Always a software project is prepared and tested as an individual unit. We pass different scenarios and expect the original values should match. One such approach is "Easymock" and in this article via a sample project, handled when and how to mock void methods. We are going to see this approach via
    3 min read
    JUnit Testcases Preparation For a Maven Project
    The quality of a software project is the desired aspect always. Programmers write code and they will do unit testing, block level testing, and sometimes integration testing too. But they will provide a few examples alone for the use cases. For example, if they are finding a number is prime or not, m
    4 min read
    Maven Project - HashMap and HashSet Collections with JUnit Testing
    In many software, we will be working with HashMap and HashSet and always there is confusion exists that when to use HashMap and when to use HashSet. As a sample project, a use case containing the "GeekAuthor" class is taken and it has different attributes namely  authorNameauthorIdareaOfInterestpubl
    7 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences