Open In App

JUnit – Inventory Stock Testing as a Maven Project

Last Updated : 31 Aug, 2022
Improve
Improve
Like Article
Like
Save
Share
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"?>
         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>
        <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.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads