How to Write Unit Tests in Java

Kunal Nalawade

Let's say you are developing an application. After long hours of coding, you manage to create some cool features. Now, you want to make sure the features are working as you want.

This involves testing if each and every piece of code works as expected. This procedure is known as Unit Testing. Different languages provide their own frameworks for testing.

In this article, I am going to show you how to write unit tests in Java. I'll first explain what testing involves and some concepts you'll need to know. Then, I'll show a few examples to help you understand better.

For this article, I assume you are familiar with Java and the IntelliJ IDE.

Project Setup

For this project, I'll be using IntelliJ IDE. If you don't have it, follow this guide to install the IDE.

In this project, we'll be using the JUnit and Mockito libraries for testing. These are the most commonly used libraries for testing in Java. You'll understand how these libraries are used as you go through the post.

To setup JUnit, follow these steps as described in this guide :

  • From the main menu, select File > New > Project.
  • Select New Project. Specify a name for the project, I'll give it junit-testing-tutorial.
  • Select Maven as a build tool and in language, select Java.
  • From the JDK list, select the JDK you want to use in the project.
  • Click Create.
  • Open pom.xml in the root directory of your project.
  • In pom.xml, press ⌘ + N , and select Add dependency.
  • This will open a tool window, type org.junit.jupiter:junit-jupiter in the search field. Locate the necessary dependency and click Add next to it.
  • Now, click Load Maven Changes in the notification that appears in the top-right corner in the editor.

Now, to set up Mockito, add these two dependencies in your pom.xml :

Note : The version may differ depending on the time you are reading this post.

To complete the setup, create a class Welcome and define your main function there.

Screenshot-2023-03-12-at-6.14.33-PM

What is Unit Testing?

Unit Testing involves testing each and every component of your code to see if they work as expected. It isolates each individual method of your code and performs tests on it. Unit tests helps make sure that your software is working as expected before releasing it.

As a developer, you'll write unit tests as soon as you finish writing a piece of code. Now, you might ask, isn't that the job of a tester? In a way, yes, a tester is responsible for testing software. But, covering every line of code adds a lot of pressure on the tester. So, it's a best practice for developers to write tests for their own code as well.

The goal of unit testing is to make sure that any new functionality does not break the existing functionality. It also helps identify any issues or bugs earlier in the development process and helps ensure that code meets quality standards set by the organisation.

Do's and Don'ts of Unit Testing

Remember the following guidelines while writing tests for your methods:

  • Do test if the expected output of a method matches the actual one.
  • Do test whether the function calls made inside the method are occurring the desired number of times.
  • Do not try to test code that is not a part of the method under test.
  • Do not make API calls, database connections, or network requests while writing your tests.

Now, let's go over some concepts you need to know before we jump into writing tests.

Assertions determine whether your test passes or fails. They compare the expected return value of a method with the actual one. There are a number of assertions you can make at the end of your test.

The Assertions class in JUnit consists of static methods that provide various conditions deciding whether the test passes or not. We'll see these methods as I walk you through each example.

The class whose methods you are testing may have some external dependencies. As mentioned before, you should not try to test code that is not part of the function under test.

But in cases where your function uses an external class, it is a good practice to mock that class – that is, have mock values instead of the actual ones. We'll use the Mockito library for this purpose.

Method Stubbing

External dependencies may not be limited to just classes, but to certain methods as well. Method stubbing should be done when your function is calling an external function in its code. In this case, you make that function return the value you want instead of calling the actual method.

For instance, the method you're testing (A) is calling an external method (B) in its implementation. B makes a database query, fetching all students with marks greater than 80. Making an actual database call isn't a good practice here. So, you stub the method and make it return a dummy list of students you need for testing.

You'll understand this better with examples. There are many other concepts that are a part of testing in Java. But, for now these three are enough for you to get started.

Steps to Perform While Testing

  • Initialize the necessary parameters you'll need to perform the test.
  • Create mock objects and stub any methods if required.
  • Call the method you are testing with the parameters you initialized in Step 1.
  • Add an assertion to check the outcome of your test. This will decide if the test passes.

You'll understand these steps more with examples. Let's start with a basic test first.

How to Write the First Test

Let's write a simple function that compares two numbers. It returns 1 if the first number is greater than the second and returns -1 otherwise.

We'll put this function inside a Basics class:

Pretty simple! Let's write the test for this class. All your tests should be located inside the test folder.

Screenshot-2023-03-13-at-5.12.04-PM

Inside the test folder, create a class BasicTests where you'll write your tests for this class. The name of the class doesn't matter, but it is a good practice to segregate tests according to each class. Also, follow a similar folder structure as the one in your main code.

Unit tests are basically a set of methods you define that test each method of your class. Inside the above class, create a method compare() with a return type of void . Again, you can name the method anything you want.

The @Test annotation indicates that this method is to be run as a test case.

Now, to test the method, you need to create the object of the above class and call the method by passing some values.

Now, use the assertEquals() method of the Assertions class to check if the expected value matches the expected one.

Our test should pass, as the value returned by the method matches the expected one. To check it, run the test by right clicking the green arrow next to the test method.

Screenshot-2023-03-13-at-5.30.14-PM

Your test results will be shown below.

Screenshot-2023-03-13-at-5.32.06-PM

More Test Examples

In the above test, we only tested one scenario. When there's branching in the function, you need to write tests for each condition. Let's introduce some more branching in the above function.

We have already tested the first branch, so let's write tests for the other two.

The @DisplayName annotation displays the text instead of the method name below. Let's run the test.

Screenshot-2023-03-13-at-6.01.15-PM

For the case where the two numbers are equal:

Sorting an Array

Now, let's write the test for the following code that sorts an array.

To write the test for this, we'll follow a similar procedure: call the method and pass an array to it. Use the assertArrayEquals() to write your assertion.

One challenge for you: write code that reverses a string and write a test case for it.

How to Create Mocks and Stubs for Testing

We have seen a few basic examples of unit tests where you made simple assertions. However, the functions you are testing may contain external dependencies like model classes and database or network connections.

Now, you can't make actual connections in your tests, as it would be very time consuming. In such cases, you mock such implementations. Let's see a few examples of mocking.

Mocking a Class

Let's have a class User with the following properties:

Click on ⌘ + N to generate getters and setters for the above properties.

Screenshot-2023-03-18-at-8.34.34-PM

Let's take a new class Mocking that uses the above object.

This class has a method that assigns certain permissions based on the user's role. It returns 1 if the permission is assigned successfully, else it returns -1 .

For demo purposes, I have only added println() statements. The actual implementation may involve setting certain properties.

In the tests file, we'll add an @ExtendWith annotation at the top since we are using Mockito. I have not shown the imports here as IntelliJ does them automatically.

So how do we write the test for the method? We'll need to mock the User object. You can do this by adding a @Mock annotation while declaring the object.

You can also use the mock() method, as it's similar.

Let's write the test method.

When you run the test, it throws a NullPointerException .

Screenshot-2023-03-18-at-8.51.26-PM

This is because the user object hasn't been initialised yet. The method you called wasn't able to use the mocked object. For this, you'll need to call the setUser method.

Now, the test gives the following error as the mocked object is initially filled with null values.

Screenshot-2023-03-18-at-8.53.53-PM

Does this mean you need to fill actual values in the mock object? No, you just need the getRole() method to return a non-null value. For that, we'll use method stubbing.

Using when()...thenReturn() tells the test to return a value when a method is called. You should stub methods only for mocked objects.

We'll do the same for the getUsername() method.

Now, if you run the test, it will pass.

Screenshot-2023-03-18-at-9.00.21-PM

Method Stubbing Example

In the above example, I simply stubbed getter methods to demonstrate method stubbing. Instead of stubbing getters, you could set the role and username with a parameterised constructor or setter methods if they are available.

But what if the user class has a method that returns all the posts containing a certain word in them?

We want this method to return all posts containing the word "awesome". If you call the actual implementation of this method, it might take a long time as the number of posts could be huge. Also, if you are mocking the User object, the posts array would be null.

In this case, you stub the method and make it return the list you want.

Method Stubbing in Database Queries

Let's see how to test methods that involve making database connections. First, create a class ApplicationDao that contains all the methods performing database queries.

Define a method that fetches the user by id and returns null if the user is not found.

Create another method to save a user into the database. This method throws an exception if the user object you are trying to save is null .

Our Mocking class will use these methods to implement its own functionalities. We'll implement one function that updates the name of a user.

The method implementation is pretty straightforward. First, get the user by id , change its username and save the updated user object. We'll write the test cases for this method.

There are two cases we need to test. The first is when the user is updated successfully. The second is when the update fails, that is when an exception is thrown.

Before writing the tests, create a mock of the ApplicationDao object as we do not want to make actual database connections.

Let's write our first test.

Create a user object for testing.

Since we are calling an external method, let's stub the method so that it returns the above User object.

Pass Mockito.anyString() to the method as we want the stub to work for any string parameter. Now, add an assertion to check if the method is working correctly.

The method returns 1 on successful update, so the test passes.

Now, let's test another scenario where the method fails and throws an exception. Simulate this scenario by making the method getUserById() return null.

This value is then passed to the save() method which in turn throws an exception. In our assertion, we'll use assertThrows() method to test whether an exception was thrown. This method takes the type of the exception and a lambda expression as parameters.

Since the exception is thrown, our test passes.

Screenshot-2023-03-26-at-4.27.07-PM

You can find the complete code here on GitHub .

As a developer, writing unit tests for your code is important. It helps you identify bugs earlier in the development process.

In this post, I started by introducing Unit Testing and explained three important concepts involved in the testing process. These gave you some background before jumping into the code.

After that, I showed you, with examples, how you can test different scenarios by using the same basic techniques in testing. I also showed how to use mock classes and methods for testing complex implementations.

Read more posts .

If you read this far, thank the author to show them you care. Say Thanks

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

Junit test user input with the coffeeMaker exercise

This is an exercise created by Sarah Heckman from NY University. It is used in a Coursera course by the university of Minnesota where I came across it. This exercise is found on many GitHub pages.

There is a coffee machine. It has a main class that needs testing with Junit. I would like to be able to test user input/output. After struggling for more than a day I couldn't work it out. It's not in the Coursera lectures. I didn't found post of anyone else struggling with it. None of the examples here at SF where helping. None of what I have been reading solved the issue.

To simplify the test I thought of first see that the initial inventory is there. That is option 5. So System.in I place 5. Given that to the main method results in a stackoverflow; given it to the mainMenu results in system under test (SUT) being Null.

How can I test user input and output with unit test?

  • program-entry-point

Edwin's user avatar

  • 1 The code is untestable without the help of some library that allows mocking of static fields. If it's not an exercises, i wouldn't even bother writing tests for such non-object-oriented code. Or try to rewrite it in object-oriented style, use a dependency on some interface that would take user input and give your object as a dependency a stubbed mock created with Mockito(or some other library). –  Barracuda Commented Sep 28, 2021 at 5:47

Know someone who can answer? Share a link to this question via email , Twitter , or Facebook .

Your answer.

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Browse other questions tagged java input junit output program-entry-point or ask your own question .

  • Featured on Meta
  • Announcing a change to the data-dump process
  • Site maintenance - Tuesday, July 23rd 2024, 8 PM - Midnight ET (12 AM - 4 AM...
  • What makes a homepage useful for logged-in users

Hot Network Questions

  • Variety without a compactification whose complement is smooth
  • Does a Fixed Sequence of Moves Solve Any Rubik's Cube Configuration When Repeated Enough Times?
  • Who were the oldest US Presidential nominees?
  • Can trusted timestamping be faked by altering some bytes within the document?
  • How did the NES's RP2A03 noise generator generator produce 32k bit long sequences despite only being 15 bits wide?
  • What is the difference between "the problem about", "the problem of", and "the problem with”?
  • Passphrase generator using German word list and Python's "secrets.choice()" to select from the list. Are those strong passphrases?
  • How can 4 chess queens attack all empty squares on a 6x6 chessboard without attacking each other?
  • The shortest way from A1 to B1
  • Braille-based Base64
  • Could an investor sue the CEO or company for not delivering on promised technological breakthroughs?
  • What is a realistic growth for a world index fund?
  • Could there be another relative language of the ancient Egyptian language closer to it than the Coptic?
  • "run-down" versus "rundown"
  • What is the faith the Ephesians were saved through (Eph 2:8)
  • Probability of a union with probability function of vector
  • The run_duration column from the msdb.dbo.sysjobhistory returns negative values
  • How to address imbalanced work assignments to new boss?
  • What is this huge mosquito looking insect?
  • One hat's number is the sum of the other 2. How did A figure out his hat number?
  • How to create a new layer that shows the number of intersecting vector layers at each point in QGIS
  • Is "avoid extra null pointer risk" a reason to avoid "introduce parameter objects"?
  • Is there any way for a character to identify another character's class?
  • Predict trajectory of a bouncing ball

programming assignment building unit tests

niyander-logo

Niyander Tech

Learn with fun

  • All Coursera Quiz Answers

Programming Assignment: Writing a Unit Test Solution

In this article i am gone to share Programming with JavaScript by meta Week 4 | Programming Assignment: Writing a Unit Test Solution with you..

Enroll Link: Programming with JavaScript

Visit this link:  Programming Assignment: Array and object iteration Solution

Lab Instructions: Unit Testing

Tips: Before you Begin

To view your code and instructions side-by-side, select the following in your VSCode toolbar:

  • View -> Editor Layout -> Two Columns
  • To view this file in Preview mode, right click on this README.md file and  Open Preview
  • Select your code file in the code tree, which will open it up in a new VSCode tab.
  • Drag your assessment code files over to the second column.
  • Great work! You can now see instructions and code at the same time.
  • Questions about using VSCode? Please see our support resources here: Visual Studio Code on Coursera

To run your JavaScript code

  • Select your JavaScript file
  • Select the “Run Code” button in the upper right hand toolbar of VSCode. Ex: It looks like a triangular “Play” button.

Task 1: Add Jest as a devDependency

Open terminal. Make sure that it’s pointing to  jest-testing  directory. Install the jest npm package using the npm install command and the –save-dev flag. Verify that the installation was completed successfully by opening the package.json file and confirming that the “devDependencies” entry lists jest similar to the following:

Task 2: Update the test entry

In the package.json file, locate the “scripts” entry, and inside of it, update the test entry to  jest .

Task 3: Code the timesTwo function

Open the timesTwo.js file and add a function named  timesTwo . The function should take number as input and return the value 2 multiplied by the number. Export the timesTwo function as a module.

Task 4: Write the first test

Code a test call with the following arguments:

  • The description that reads: “returns the number times 2”.
  • The second argument should expect the call to the timesTwo function, when passed the number 10, to be 20.

Task 5: Run the first test

With the terminal pointed at the  jest-testing  directory, run the test script using npm.

  • Copy & paste this code on Files..
  • And save your file and then submit.

First Change in this file timesTwo.js

Second Change in this file timesTwo.test.js

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Save my name, email, and website in this browser for the next time I comment.

  • GDPR Privacy Policy
  • Privacy Policy
  • Terms and Conditions

Greetings, Hey i am Niyander, and I hail from India, we strive to impart knowledge and offer assistance to those in need.

IMAGES

  1. Building Unit Tests: Programming Assignment Solution |Coursera

    programming assignment building unit tests

  2. Programming Assignment Unit 5

    programming assignment building unit tests

  3. Unit 4 Programming Assignment

    programming assignment building unit tests

  4. Mastering Unit Testing in Python: A Guide for Developers

    programming assignment building unit tests

  5. Programming Assignment Unit 7 Solution v1

    programming assignment building unit tests

  6. In this programming assignment, you will be building

    programming assignment building unit tests

VIDEO

  1. Are Unit Tests Necessary in Software Engineering?@StephenSamuelsen

  2. Assignment (Building a Model for Automating a Workflow)

  3. How to write an A+ assignment EVERY TIME ✍🏼👩🏻‍⚕

  4. CODING TEST 2

  5. Coursera Programming Assignment: Writing a Unit Test solution (Week 4)

  6. Revit Tutorial Excavation Feature Toposolid

COMMENTS

  1. Building Unit Tests with JUnit

    In this assignment, you'll get some practice at building effective unit tests. Using the example from our videos, you'll be developing tests for the Demo class, including the isTriangle() and main() methods. Your task is to create a file, DemoTest.java, which properly tests the Demo class to ensure it is working properly.

  2. Faaizz/introduction_to_software_testing

    Exercises from "Introduction to Software Testing" course by the University of Minnesota via Coursera. Building Unit Tests with JUnit; Building a Test Plan; Efficient Unit Testing with JUnit and Code Coverage with JaCoCo; Test Doubles with Mockito

  3. mdalmamunit427/Programming-Assignment-Writing-a-Unit-Test

    Make sure that it's pointing to jest-testing directory. Install the jest npm package using the npm install command and the --save-dev flag. Verify that the installation was completed successfully by opening the package.json file and confirming that the "devDependencies" entry lists jest similar to the following:

  4. Coursera Programming Assignment: Writing a Unit Test solution ...

    In this video, I will show you how to solve Programming Assignment: Writing a Unit Test. Course Title: Programming with JavaScriptWeek: 4Assignment name: Pr...

  5. 13 Tips for Writing Useful Unit Tests

    In this article, I'll cover some tips and pointers about how to unit test your code. Here we go. 1. Test One Thing at a Time in Isolation. This is probably the baseline rule to follow when it comes to unit tests. All classes should be tested in isolation. They should not depend on anything other than mocks and stubs.

  6. Unit Testing Tutorial: 6 Best Practices to Get Up To Speed

    9. Use Mock Objects when Necessary. Mock objects can be used to simulate dependencies, such as databases or web services, which can make testing more reliable and faster. By using mock objects, developers can isolate the code being tested and focus on the behavior of the unit being tested.

  7. How to Write Unit Tests in Java

    Specify a name for the project, I'll give it junit-testing-tutorial. Select Maven as a build tool and in language, select Java. From the JDK list, select the JDK you want to use in the project. Click Create. Open pom.xml in the root directory of your project. In pom.xml, press ⌘ + N, and select Add dependency.

  8. PDF DIT635

    it. Instead, your unit tests should target the other classes of the system. However, we would recommend performing some exploratory testing (human-driven exploration) using the Main class to understand how the system functionality should function before you write unit tests. 2) Unit tests implemented in the JUnit framework 3) Instructions on ...

  9. Building Unit Tests: Programming Assignment Solution |Coursera

    Course Name :Introduction to Software TestingGithub Linkhttps://github.com/Dipeshshome/Programming-Assignment-Introduction-to-Software-Testing-Week-1

  10. Building Unit Tests: Week 1 Solution

    You could find DemoTest.java file on my GitHub repo: https://github.com/EveBogdanova/SoftwareTesting/blob/master/Building%20Unit%20Tests/src/DemoTest.java

  11. Unit Testing Best Practices

    Source. Disclaimer: This is a set of things I consider very useful when writing unit tests.I call them best practices because they allow me to write good, quality tests that are easier to read, more maintainable, and better describe business needs.. These points might be subjective, you might have other opinions or have more items. That's fine. Do not hesitate to put your opinions in the ...

  12. How to write good Unit Tests in Functional Programming

    Idiomatic functional programming involves mostly side effect-free pieces of code, which makes unit testing easier in general. Defining a unit test typically involves asserting a logical property about the function under test, rather than building large amounts of fragile scaffolding just to establish a suitable test environment.

  13. Building Unit Tests with JUnit

    Exercises from "Introduction to Software Testing" course by the University of Minnesota via Coursera - Faaizz/introduction_to_software_testing

  14. GitHub

    Inside the project, you will find the functional code, a couple of unit tests to get you started. The goal is to construct a sufficient number of unit tests to find most of bugs in the "buggy" version of the coffee maker that is included. You should be able to detect at least 5 bugs in the code using your unit tests.

  15. Junit test user input with the coffeeMaker exercise

    To simplify the test I thought of first see that the initial inventory is there. That is option 5. So System.in I place 5. Given that to the main method results in a stackoverflow; given it to the mainMenu results in system under test (SUT) being Null. How can I test user input and output with unit test?

  16. Programming Assignment: Writing a Unit Test Solution

    Code a test call with the following arguments: The description that reads: "returns the number times 2". The second argument should expect the call to the timesTwo function, when passed the number 10, to be 20. Task 5: Run the first test. With the terminal pointed at the jest-testing directory, run the test script using npm.

  17. Coursera-Introduction-to-Software-Testing-education-source ...

    ducnguyenedures / Coursera-Introduction-to-Software-Testing-education-source Public Notifications You must be signed in to change notification settings Fork 2

  18. SoftwareTestingCourse/Building Unit Tests/src/DemoTest.java at ...

    Saved searches Use saved searches to filter your results more quickly