Software Testing: Unit Test Cases for Simple Java Programs

Swati Rajwal
Geek Culture
Published in
6 min readJun 6, 2021

--

This article is intended for any individual who is simply beginning with unit testing in java. Here, I have written three very simple java programs and their corresponding test cases to help you understand the concept. This article will cover everything from installing necessary packages to running your very first unit test case for a Java program.

Why Unit Testing?

If you are a CS grad or a working professional, you might have come across terms like Test-driven development or TDD. According to Agile Alliance, TDD can be defined as :

A style of programming in which three activities are tightly interwoven: coding, testing (in the form of writing unit tests), and design.

This means that writing unit test cases is crucial for TDD-based software development. I recommend that unit test cases should be a part of your development rituals as it minimizes errors from a developer's side. You need not rely on the tester to report small bugs which could have been avoided otherwise. At times, I have seen that unit test cases helped me improve my work by reducing silly errors. So you see, there is a tiny bit of tester in a developer too!

Setting-up your System

Let’s begin with setting your system. Please note that this article is a quickstart to run your first unit test case for a really simple java program. I am certain that once you get that bug report running (coming up in the next sections), you will try to find more details. Internet is a big knowledge hub and you can find materials to understand the technical details.

For this article, I am using Visual Studio (VS) Code.

  1. Install Java: There can be two situations. You have VS Code but java is not configured or you do not have either VS code or java. I highly recommend you to go through this link. It is super easy to follow if you fall under either category.
  2. Enabling extensions: Once the VS Code is configured with Java, you need to enable the Java Test Runner, Language Support for Java by Red Hat, and Debugger for Java extensions. These tools will help you to run/debug test cases, see test reports & test logs, and many others.

Launching Visual Studio Code

  1. Create a folder where you wish to save your Java code and test files.
  2. On the top directory navigation bar type “cmd” as shown in fig.1.
  3. Hit enter and the command line terminal opens up. Then type “code .”
  4. Press enter and voilà! You just launched the VS Code workspace. That’s cool, isn’t it?
Figure 1: Directory Navigation bar with “cmd”

Creating a Java Project

GIF 1: Creating Java Project
  1. Stay on the VS Code page as mentioned above and press Ctrl+Shift+p
  2. Then select “java: create java project”.
  3. Follow along with the prompts and keep selecting the necessary details.
  4. Maven is a build automation tool used primarily for Java projects. In this demo, I have selected Maven. You can configure the Java project with other alternatives like Gradle, etc.
  5. Once everything is done, your new project should be visible and look like this:
Figure 2: Java Project in VS Code

Running Test Cases

Before you run any file, I highly recommend that you go through the Java project thoroughly. Try to spend some time understanding the project structure and then proceed with the next steps. Also, the code for this entire tutorial can be found in the Github repository.

  1. First of all, run your java file that contains the main code. There are many ways to run a file. One of them is to right-click on the code file and select “Run java”.
  2. Now you should see the anticipated output in the terminal.
  3. In the project you will observe some changes like the creation of class file (it’s java, after all!), the addition of Run Test and Debug Test shortcuts (or, CodeLens) above the class, and method definition by the extension that we installed sometime back.
  4. Run the java test file (AppTest.java in this demo) and the installed extensions will add codeLens like Run Test | Debug Test | ✓. The checkmark shows the test reports. This report contains various details like the test cases that passed or failed, and re-run the test cases, etc.
  5. And that is it! For this example, we only had one test case namely “shouldAnswerWithTrue” which happened to have passed successfully! You should definitely play around with the code giving different inputs to see if your test case fails or not. Go ahead, take some time and come back to see few other simple java codes for which test cases will be generated.

Writing first Unit Test Case

In this example, I have considered a simple java program that evaluates the product of two numbers and prints it.

Given below is the unit test case to check if the product so generated is correct or not.

package com.example;
import static org.junit.Assert.assertEquals;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class AppTest
{
private App app;
@Before
public void setUp() throws Exception {
app = new App();
}
@After
public void tearDown() throws Exception {
}
@Test// unit test case that will check whether the method returns the
// anticipated output or not
public void testMultiplication() {
int result = app.multiply(10, 5);
assertEquals(result,40);
}
}

If you notice in the test file I have mentioned that 40 in the assertEquals method which is clearly wrong as the product of 10 and 5 should be 50. Let’s see what happens when this unit test case runs.

GIF 2: Running the first test case

I hope by now you get why this error occurred. Try to rectify and run the code as mentioned before.

Multiple Test Cases

I have added more methods in the java file and the corresponding unit test cases in the test file. The test file looks like this:

@Test
//unit test case that will check whether the method returns
//the anticipated output or not
public void testMultiplication() {
int result = app.multiply(10, 5);
assertEquals(result,40);
}
public void testDivision() {
int result1 = app.divide(10, 5);
assertEquals(result1,40);
}
public void testAddition() {
int result2 = app.add(10, 5);
assertEquals(result2,40);
}
public void testSubtraction() {
int result3 = app.subtract(10, 5);
assertEquals(result3,40);
}

Let’s see how these test cases look like.

GIF 3: More unit test cases

Conclusion

This article definitely did not cover all the aspects of unit testing however is unquestionably useful to somebody who wishes to begin writing java unit test cases today. I have included only the simplest examples, but you can write more complex cases. I will certainly attempt to write more articles to cover boundary value analysis or related concepts. For now, I hope the current article will be useful to you.

Also, you can ask me a question on Twitter and LinkedIn!

Thank you.

--

--

Swati Rajwal
Geek Culture

Just another human being on this beautiful planet.