JUnit - Inventory Stock Testing as a Maven Project
Last Updated : 31 Aug, 2022
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:
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)); //.... }
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.
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