Examples Java Code Geeks

JUnit Test Void Method Example

Photo of Vinod Kumar Kashyap

In this example, we shall show you to test void methods. In JUnit Test Void Method example we will learn how we can test the void methods using the JUnit. In our previous tutorials, we have learned a lot about the JUnit and its various techniques about testing. But in our previous tutorials we haven’t seen how we can test void methods.

how to write the junit for void method

  In this example, we will see how we can cover examples of some of the scenarios where we need to test the void methods. We will be using Maven as our build and dependency tool for this example.

1. Introduction

JUnit testing framework will help you test all your methods. It is a major tool in the arsenal of Java developers. We can test all type of methods irrespective of the method returning any value or not.

In our previous tutorials , we have seen many ways to test the methods those returning the value. In this example we will test those methods that don’t return any value .

Above line is from JUnit docs and tells everything about the methods.

2. Technologies Used

We will be using the following technologies in our example.

  • Java 1.8 : Language to write our example. We will be using the latest Java version i.e. 1.8
  • JUnit 4.12 : testing framework for unit testing.
  • Maven : build and dependency tool. It will be used to fetch the JUnit jar from maven repository.
  • Eclipse : IDE for writing code. You can use any IDE of your choice as it supports Maven integration

3. Project Setup

Let’s begin with creating our example.

Open eclipse. Click File -> New -> Maven Project .See below screen for modifications and click on Next button.

On next screen fill in all the details as shown below and click on the Finish button.

With this, we are ready with the blank Maven project. At this point, our example is an empty Maven project with a blank skeleton. Let’s start with our example from here. We need to write some initial steps before start coding.

4. JUnit Test Void Method Example

First of all we need to create the following lines in pom.xml file. These lines will fetch the JUnit dependency. It also tells Maven to use Java 1.8 for compiling our code.

4.1 Java Classes

Now start by writing a java class that will prepare the core for our example. We will create a simple class which will be used later in this example for testing.

MyList.java

As you see in this class we have some void methods that need to be tested. This is a simple example explaining the behavior of the void methods. In this example, we are imitating the behavior of List interface for adding and removing of an element.

We will simply create a List and then add and remove from that, but with help of our class. At line no 17 , we are also throwing the NoSuchElementException() . We will also see how we can test this exception in our example. We have covered it here as it is thrown by the void method.

4.2 JUnit Test Class

how to write the junit for void method

We will contact you soon.

MyListTest.java

4.3 Code Explained

Let’s examine each method in details and how we are testing it.

  • init() is used to initialize the List of our class. We are adding some default elements, in our case fruits.
  • testSize() is used to check size of the list.
  • testAdd() is a void method. We are simply adding the new element to the existing list. This method is not returning any value. So the point is how we can test it? And the answer to this question is simple as that. We simply check the size of the list. If it is increased by one (as we added one element) then we can easily check the size. We have used the assertEquals here( see line no 30 )
  • testRemove() is used to check the removal of an element from list. in this case, the size of the list should be decreased. Same way as in testAdd() , here also we are using assertEquals for testing.
  • testRemoveException() is used to test the exception thrown by the method. See how we have captured the exception. In this method we are removing an element which is not present in the list. In such case this method will thrown an exception. If we do not catch that exception, the test case will fail eventually. So to make our test case pass we have to catch it using the @Test(expected = NoSuchElementException.class) . It is a very clean way of catching exception and testing it.
  • destroy() is used to remove all elements that we have added to our collection. It is to be noted that @Before and @After will run before and after every test case .

Output We can analyze the output of our example in the JUnit tab of eclipse.

5. Conclusion

In this example, we have learned that how we can JUnit Test Void Method. We have also learned that how to catch the exception if it is thrown by a void method. Actually testing mechanism is same for all methods, but void methods are special as we don’t have any returning value to be matched for testing.

But as we have previously said that the method may not be returning anything but it may be altering the behaviour of our program somewhere. So we simply test that case and then it is easy to implement it.

6. Download the Eclipse Project

This is a JUnit Test Void Method example.

how to write the junit for void method

Vinod Kumar Kashyap

Related articles.

how to write the junit for void method

JUnit AssertThat Example

Junit mockito when thenreturn example, junit setup / teardown example, junit code coverage, junit test constructor example, junit report generation example, junit no runnable methods, “no junit tests found” error solution.

guest

This site uses Akismet to reduce spam. Learn how your comment data is processed .

Jagatdeep Chakraborty

This solution is not generic for all void methods.

abhishek Kumar

Exactly this is not at all generic void testing. Rather than checking void test this post is checking list size that is irrelevant in current topic context

Benjamin Teskey

I think that the content in this article is useful for explaining how JUnit handles state change between tests, but it would be better if it addressed the significance of testing void. I know there really isn’t any, but it is what the article says it will address.

Paramita

This is not at all a generic example and please make another example which will be more useful.

  • +(1) 647-467-4396
  • hello@knoldus.com

Knoldus_logo_blog

  • hello@knoldus.com

Unit testing void methods with Mockito and JUnit

Junit tests using Mockito & PowerMockito - Bhasaka

Writing functionality is the main focus whenever we are writing a software program, but it is equally important that we make sure our code works the way we intended it to. And how do we do that? By writing unit test cases. They are used to test the smallest functionality of code. Unit test cases are an essential part of software development. In this blog, we are going to cover one of the testing scenarios in which we will be writing Unit test cases for void functions with Mockito.

How to Test void methods

As we already know that our aim is to test void methods in a class but it is also really important to understand why do we test void methods. 

Whenever we write unit test cases for any method we expect a return value from the method and generally use assert for checking if the functions return the value that we expect it to return, but in the case of void methods, they do not return any value. So how do we check if our method is functioning properly? Let’s see using an example.

In this example, we are creating Two classes Information and Publishing .

The Information class looks like this:

As we can see the method sendInformationForPublishing() is a void method. The logic for the method is simple. It takes a Person object as a parameter and passes the object to the method of Publishing class.

The method publishInformation() is also a void method.

Let us now see how we can write unit test cases for this simple implementation.

Using the verify() method

Whenever we mock a void method we do not expect a return value that is why we can only verify whether that method is being called or not. 

Features of verify() :

  • Mockito provides us with a verify() method which lets us verify whether the mock void method is being called or not. 
  • It lets us check the number of methods invocations. So if the method invocation returns to be zero we would know that our mock method is not being called.

The verify method takes two arguments. The mock method object and the number of invocations you want to verify. The expected number of invocations is passed in the times() method. Let’s see how the test case will look like.

As our function will call the publishInformation() only once so we have passed the value 1 in the times() function. We know that when our test case will call the mocked publishInformation() method, it will not do anything. We need to let Mockito know of this behavior. For this, we use the doNothing() method. Which will in simple terms let Mockito know that it needs to do nothing when the given method is called.

how to write the junit for void method

If we change the number of invocations to any other value the test case should fail.

Here I changed the number of invocations to 2.

how to write the junit for void method

That’s it! It’s that simple. This is how we can unit test the void methods. 

The GitHub link for this implementation is provided here . Simply clone it have fun!

Checkout more fun blogs on Java and JUnit on Knoldus Blogs .

This image has an empty alt attribute; its file name is footer-2.jpg

Share the Knol:

  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Twitter (Opens in new window)
  • Click to share on Telegram (Opens in new window)
  • Click to share on Facebook (Opens in new window)

Discover more from Knoldus Blogs

Subscribe now to keep reading and get access to the full archive.

Type your email…

Continue reading

IntelliJ IDEA

IntelliJ IDEA – the Leading Java and Kotlin IDE, by JetBrains

  • Twitter Twitter
  • Facebook Facebook
  • Youtube Youtube

Writing Tests with JUnit 5

Trisha Gee

In this tutorial we’re going to look at features of JUnit 5 that can make it easier for us to write effective and readable automated tests. All code in this tutorial can be found in this GitHub repository .

This blog post covers the same material as the video. This provides an easy way for people to skim the content quickly if they prefer reading to watching, and to give the reader/watcher code samples and links to additional information.

Setting up Gradle for JUnit 5

This tutorial uses Gradle , for information on how to add JUnit 5 via Maven take a look at our blog and video on Migrating to JUnit 5 from JUnit 4 .

Given a Gradle build file , use ⌘N (macOS) or Alt+Insert (Windows/Linux) to add a new dependency. Typing "junit" in the artifact search box should give a list of possible dependencies.

JUnit 5 dependencies

Use Tab to jump into the dependencies list and use the down arrow until org.junit.jupiter:junit-jupiter is selected. Use the right arrow to open up the version options for this dependency, and choose version 5.6.2 (the most recent production version at the time of writing).

JUnit 5.6.2

NOTE: if you try to search for a dependency and you don’t get the results you expect (either no results, or the versions seem out of date), make sure IntelliJ IDEA has an updated Maven Repository via the settings.

You should see an icon in the top right of the Gradle build file when it has been changed. You must load the Gradle changes if you want IntelliJ IDEA to apply them.

how to write the junit for void method

Click on the icon, or use ⇧⌘I , or Ctrl+Shift+O on Windows and Linux, to load the changes. Once the Gradle dependency changes have been loaded, we can see the junit-jupiter dependencies in the External Libraries section of our project window.

how to write the junit for void method

There’s one last step we need to do for Gradle in order to correctly use JUnit 5. We need to tell Gradle to use the JUnit Platform when running the tests, by adding useJUnitPlatform() to the test section. The final build.gradle file should look like this:

Creating and Running a Test

Now the JUnit dependency is set up correctly, we can create our first JUnit 5 test. Create an ExampleTest using the shortcut to generate code ( ⌘N or Alt+Insert ) in the project window.

Create a new test class

Use the same shortcut again inside the class itself to get IntelliJ IDEA to generate a new valid test method for us.

how to write the junit for void method

If you’re familiar with JUnit 4, you’ll see the basic test method looks exactly the same, and we can use whichever format name we usually use for our tests. The only difference with JUnit 5 is that it uses the Test annotation from the jupiter package.

JUnit 5 has an Assertions class for all the common assertions we might want to make. We can use partial completion to find the assertion that we want, for example assertEquals.

Code completion

Now we have our most basic test case:

Run it to make sure everything works. You can run with:

  • Run : ⌃R or Shift+F10
  • Run Context Configuration: ⌃⇧R or Ctrl+Shift+F10 (Windows/Linux) with the caret inside this method to run just this single test method. If the caret is outside the method, this will run all the tests in the class.
  • You can click the green arrow in the gutter of either the test method (to run just the test) or the class name (to run all tests in the class).

When the test runs, IntelliJ IDEA shows the result in the run tool window ( ⌘4 or Alt+4 ). If the details of the passing tests are hidden, we can show all the tests that passed by clicking on the tick in the top left.

Run window

Double clicking on the test method name takes us back to that method in the code.

One thing to note for JUnit 5 tests is that the test method doesn’t need to be public in order to work. IntelliJ IDEA will let you know if the class or method can have reduced visibility and still work. Use Alt+Enter to have the IDE remove public from the class declaration, and re-run the test to make sure it works as expected.

Change the test so that it should fail:

When a test fails, IntelliJ IDEA shows the failing test in amber since the test failed an assertion, rather than causing an error (which would be shown in red). We can see the expected value and the actual value side by side, and this should give us an idea of what failed and how.

Failed tests

In our case the cause of the problem should be quite clear since we intentionally put the wrong number in as the "actual" argument.

Configuration: Parameter Hints

Note that IntelliJ IDEA’s parameter hints feature is really helpful for assertion methods. It’s not clear from the method signature which argument is the expected result and which is the actual result. IntelliJ IDEA shows the names of the method parameters as hints, so we can see at a glance which is which.

Parameter name hints

If we decide this is too much noise in the editor, we can turn off hints for a specific method using Alt+Enter on the hint and selecting "Do not show hints for current method". We can also configure the parameter hints from the IDE preferences, in Editor -> Inlay Hints -> Java -> Parameter hints . We can turn hints on or off and configure which types of methods show hints. We can also see the Exclude list, and remove items from the Exclude list if we decide we want to see hints for this method.

Configuration: Test Runner

We can configure how IntelliJ IDEA runs our unit tests if we’re using Gradle . By default IntelliJ IDEA uses Gradle to build and run the code and tests in Gradle projects. This ensures that when we run the application or tests in the IDE, it works the same way as it would in other environments like the command line or a continuous integration environment. It also ensures that any complex build or setup logic, or code generation, is done. However we might choose to use the IntelliJ IDEA runner to run our tests. In some circumstances this might be faster than using Gradle and provide a faster feedback loop.

Disabling or ignoring tests

Quite often we want to say we don’t want a test to be run. This is common with Test Driven Development as tests will, by definition, fail when we first write them. JUnit 5 supports this with a @Disabled annotation. We can add descriptive text to state why the test is not to be run.

NOTE: tests should usually only be disabled for a short period of time, until the code they are testing is working. If a test is disabled for a long time, perhaps because we don’t know why it doesn’t work or what its expected behaviour is, it’s not adding any value to the test suite. A test like this should be removed.

Like passing tests, IntelliJ IDEA usually hides the full list of disabled tests so we can focus on just the failures. Show all disabled tests by clicking on the grey disabled icon. Click on the test name to see the reason the test was disabled.

Running disabled tests

Helpful test names for display

JUnit 5 supports a @DisplayName for the test method, so we can add a helpful descriptive name for the test.

When we run the test, it’s this DisplayName that shows in the run window:

Test display name

Not only does this encourage us to be descriptive, since it’s a text string and not a method name, it supports special characters, which can help readability.

IDE Tip: Live Templates

If we have a standard template for new test methods that we’d like to follow, we could change the default test method template in IntelliJ IDEA , or we could write a Live Template which helps us to create new test methods that look exactly the way we want.

Let’s create a live template to generate a new test method with a DisplayName that is initially converted into a CamelCase and applied to the method name. This encourages us to use the DisplayName annotation to write readable test descriptions, and uses them to create valid method names so the method name is also helpful. The code our Live Template should generate will look something like this:

It’s good practice to have generated tests automatically insert a fail into the generated method – any test should fail first even if we haven’t finished writing it yet

To create this live template , open the preferences and go to Editor -> Live Templates .

Live template preferences

Using the "+" in the top right of the scroll pane, create a new live template group called "Test". With this group selected, using the "+" again to create a new live template.

In the live template details in the bottom of the screen:

  • Give the template an abbreviation of "test"
  • Give it a helpful description, like "JUnit 5 test method"

The key to live templates is creating the template text. This is quite a complex template, so the text is quite advanced:

NOTE: Use fully qualified names (package name plus class name) for the annotations so IntelliJ IDEA knows exactly which class you want. Tick "Shorten FQ names" to have IntelliJ IDEA automatically add the correct import and use only the class name in the annotation.

I like to tick:

  • Reformat according to style
  • Use static import if possible
  • Shorten FQ names

on my live templates, then, when the code is inserted into the class file it usually follows the same standards as the rest of the application.

Test live template

You need to define the scope the live template applies to, otherwise the IDE won’t know in which sorts of files and at which time it should suggest this template. Click the "define" link next to the "No applicable contexts" warning, and select Java -> Declaration . IntelliJ IDEA will now add this to the list of suggestions when we’re in a Java class file.

Notice the variables in the template. Some of these are built in to the IDE, for example $END is where the caret will end up when the live template finishes inserting all the code. Some are values you’re going to have to define. Let’s define those now. Click on the "Edit variables" button to bring up the variables window.

Live template variables

Set the following values for the variables:

  • Expression=<leave blank>
  • Default value= "Test name"
  • Expression= camelCase(TEST_NAME)
  • Default value= "methodName"
  • Default value= "org.junit.jupiter.api.Assertions.fail(\"Not implemented\");"
  • Tick "Skip if defined"

Press OK on the variables window, and OK on the preferences window.

Check the live template in the editor. Make sure the caret is inside the Java test class, but outside of an existing test method. Type test and press tab. IntelliJ IDEA should generate a test method skeleton, and the caret should be in the value of the DisplayName annotation. Type a readable test description here, and you should see the text description is turned into a valid Java camelCase method name as well. Press Enter when you’ve finished the value for DisplayName , and the caret should move to select the method name in case you want to edit it. Pressing Enter again should place the caret above the fail call.

Using a live template

Multiple Assertions

As we already saw, JUnit 5 supports standard assertions that may be familiar if we’ve used other testing frameworks. In the real world, we often have to check more than one thing to prove something worked the way we expected. Take a list, for example. If we want to check every item in it is correct, we might write multiple assertions to check each value.

This works, it will certainly pass if all the items in the list are as expected. The problem comes when one of the assertions fails. Change the first assertion so it fails:

The output shows that the test fails, and why that was.

Multiple assertions

What we don’t know though is whether the other assertions passed or failed, because JUnit won’t run the assertions after the first failure. You can see that if you change all the other assertions to fail:

NOTE: you can use column selection mode or multiple carets to easily edit all the "expected" values at once.

Run the test to see once again that only the first assertion fails, we have no idea the others are also broken.

Multiple assertions with one failure

This could be a problem – we’d go back and fix the first assertion, re-run the test, have to fix the next one, re-run the test, and so-on. This is not the fast feedback we’re looking for.

JUnit 5 supports an assertAll assertion . This will check every assertion even if one of them fails. We do this by putting all of the assertions we want to group together into the assertAll call as a series of lambda expressions.

Let’s keep the test with values that should fail, so we can see what happens when we run a failing assertAll :

Multiple assertions multiple failures

We can see that all the assertions failed – they were all run even though the first one failed. This makes it much easier for us to see the issues and fix them all in one pass, instead of having to repeatedly re-run the test.

Make the changes to fix the test:

Re-running the test should show everything works:

All assertions pass

Assumptions

Now let’s look at assumptions in JUnit 5. Later versions of JUnit 4 supported assumptions , but those of us who are used to working with older tests might not have come across this concept before. We may want to write tests that only run given some set of circumstances are true – for example, if we’re using a particular type of storage, or we’re using a particular library version. This might be more applicable to system or integration tests than unit tests. In these cases we can set an assumption at the start of the test, and the test will only be run if the criteria for that assumption are met. Let’s write a test that should only be run if we’re using an API version that’s higher than ten.

When we run the test, we see that this test runs and passes as expected because the Fixture is returning an API version higher than 10 (for this tutorial, Fixture.apiVersion() returns 13).

Assumption was true

Let’s flip the check in the assumption, so the test only runs if the API version is less than 10:

Rerun the test – it should not go green. Since our API version is higher than ten, this check returns false, the assumption is not met, and the test is not run. It shows as a disabled or ignored test:

Assumption was false

Data Driven Tests

Earlier we saw that we can use assertAll to group a number of assertions and make sure they’re all run. This is one way of performing multiple checks. There are other cases where we might want to do the same set of checks on different sets of data. For this, we can use parameterised tests . Parameterised tests are where we can pass data into the test as parameters, and with JUnit 5 there are a number of different ways to do this ( see the documentation , it’s very good). We’re going to look at the simplest approach to show how it works.

Let’s use the @ValueSource annotation to give the test method a series of individual values to test.

JUnit 5 supports many different types of array input for this annotation, let’s use an array of hardcoded ints for this test. Each one of these values will be passed into the method individually, so the test method needs a single int parameter, expectedNumberOfSides , to pass the value in.

NOTE: IntelliJ IDEA can help us with parameterised tests in JUnit 5. It lets us know that if we’re using a ValueSource annotation, we shouldn’t be using the @Test annotation but ParameterizedTest instead. We can use Alt+Enter to get IntelliJ IDEA to change any @Test annotations to @ParameterizedTest .

Inside the test method, call the constructor of Shape , passing in the number of sides given to us, and check that the Shape can give us the correct number of sides.

Run the test. In fact, the test runs more than once. The test is run for each one of the int values we put into the ValueSource annotation.

Running parameterised tests

We can change the way these individual tests are shown in the results, by creating a custom name in the ParameterizedTest annotation. For this test, show the value of the number of sides the shape is being created with by using the first parameter ( expectedNumberOfSides ) as the test instance name:

When the test is run, we see the run window shows the number of sides used as the name for each test instance:

Customising parameterised test names

Checking Exceptions

Parameterized tests are very helpful for testing large sets of valid data, but they’re also really useful for checking lots of invalid input with the same assertions.

Create a new test to check invalid input. Set up a new ValueSource of int s, but this time the int values will all be invalid numbers of sides for a polygon. Assume that you need to check for too few sides, and assume the code doesn’t support creating Shapes with a very large number of sides:

At this point we should be asking ourselves: "what’s the expected behaviour when the input is invalid?". If we decide that the constructor should be throwing an exception when it is passed invalid values, we can check that with an assertThrows . We tell it which Exception we expect to be thrown, and we use a lambda expression to pass in the method that we expect to throw the exception.

Grouping tests with @Nested

In this final section we’re going to look at one of my favourite features of JUnit 5, nested tests . Nested tests allow us to group specific types of tests together inside a larger class. There are lots of reasons we might want to do this. For example, to group together tests with similar setup or tear down, but that are not so different from other tests in the class that they need to be in their own test file.

We’re going to use this feature to group together all the tests that require a Shape that’s already been set up.

Create an inner class, and add the Nested annotation. We can also add a DisplayName to this the same way we would to a test method.

The nested class can contain fields, of course, and we can use these to store values that all the tests inside this inner class will need. Let’s create a simple Shape to use in these tests.

We can even create Nested classes inside our Nested class. This can be useful to do further grouping. We’re going to use it in this example to group together Happy Path tests, the tests that check everything works as expected under normal circumstances.

Now we can create our specific tests inside our nested classes. With nested classes we’ll probably want to define a naming convention that makes sense when the test results are printed, which we’ll see in a minute. Let’s make this first happy path test a simple check that shows the Shape returns the correct number of sides. We can then create another test which checks the correct description is returned for our shape.

(Note that I’m just showing the inner-most class in this snippet, but it’s still part of the larger class)

Now let’s create a group for tests that show what behviour is not supported, or is not expected. Let’s say that in our example two Shapes with the same number of sides are not supposed to actually be the same shape. This is the listing for the whole class :

If we run all the tests in the class ( ⌃R or Shift+F10 ), we can see our nested tests in the test results. We can see the grouping means the results of similar tests are all grouped together. We can also see how the display name can help us to understand the grouping of the tests.

Run nested tests

IDE Tip: Code Folding

If all of these annotations are adding too much noise to the editor, we can always collapse them by pressing on the minus in the gutter, or by using the keyboard shortcut to fold code, ⌘. or Ctrl+. – where "." is the full stop or period on the keyboard. We can hover over the collapsed annotations to see them.

Find Usages

This tutorial has just scratched the surface of the features offered by JUnit 5. To find out more, go to the JUnit 5 documentation , it covers a huge host of topics, including showing the features we’ve seen in this video in more detail. It also covers the steps to take to migrate to JUnit 5 from JUnit 4, which was also covered in blog and video .

Top shortcuts

This blog post includes some shortcuts, but many more were demonstrated in the video and not all of them were mentioned here:

  • ⌘[ or Ctrl+Alt+left arrow Navigate back – makes it easy to navigate between all the places you’ve been while writing code and running tests
  • ⌘⇧T or Ctrl + Shift + T Navigate between test and test subject. This is explored in the Top 5 Navigation Tips (blog and video).
  • ⌃⇧J or Ctrl+Shift+J Join Lines to create compiling code.
  • ⇧⌘⏎ or Ctrl+Shift+Enter Complete Statement close off the brackets and statement, and it also formats the code too.
  • ⌃⇧Space or Ctrl+Shift+Space Smart completion
  • Migrating from JUnit 4 to JUnit 5 – blog, with embedded video
  • Unit Testing and Coverage in IntelliJ IDEA (video)
  • Editor Tips & Tricks (blog and video)
  • Top 15 IntelliJ IDEA Shortcuts Blog (blog and video)

Download IntelliJ IDEA

how to write the junit for void method

Subscribe to IntelliJ IDEA Blog updates

By submitting this form, I agree that JetBrains s.r.o. ("JetBrains") may use my name, email address, and location data to send me newsletters, including commercial communications, and to process my personal data for this purpose. I agree that JetBrains may process said data using third-party services for this purpose in accordance with the JetBrains Privacy Policy . I understand that I can revoke this consent at any time in my profile . In addition, an unsubscribe link is included in each email.

Thanks, we've got you!

Discover more

how to write the junit for void method

Debugger Upskill: Debug Without Breakpoints

In a typical debugging scenario, you would set breakpoints to tell the debugger when to suspend your program. A breakpoint usually corresponds to the moment that marks the starting point for further investigation. Deciding where to set a breakpoint can be challenging. There might be situations wher…

Igor Kulakov

Java Annotated Monthly – May 2024

Welcome to the latest edition of Java Annotated Monthly! This time around, we're thrilled to have Holly Cummins on board for our featured content section. As usual, we've gathered a bunch of fresh updates, insights, and interesting discussions from across the tech scene in April. So, grab your…

Irina Mariasova

Getting Started with Databases in IntelliJ IDEA 

Have you ever wondered how IntelliJ IDEA handles databases? Well, today is the perfect opportunity to find out in our database tutorial on initial setups and first steps.   All of the features you’ll need when working with databases are available out of the box in IntelliJ IDEA Ultimate…

JPA Buddy in IntelliJ IDEA: A Complete Walkthrough

The What, Why, and How of JPA Buddy in IntelliJ IDEA

Master JPA entity management with JPA Buddy in IntelliJ IDEA! Our latest article shows you how to simplify your workflow and reduce boilerplate code.

logo

Java Unit Test void methods

  • Post author: Chinmoy
  • Post published: August 17, 2020

There are many ways we can test a void method and in this post we will see few of them.

Using Mockito

Void methods can be used with Mockito’s doNothing(), doThrow(), and doAnswer() methods.

doNothing()

doThrow() : test when our method throw some exception

doAnswer() : Use this to do some operations when void method is called

You Might Also Like

Rest http methods, springboot with resttemplate calling jira apis, leave a reply cancel reply.

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

Roy Tutorials

Technical… Theoretical… Practical…

Java Junit 5 Mockito doNothing() Example

In this tutorial I am going to show you how to work with Mockito ‘s doNothing() in Java Junit 5 API. Mockito ‘s doNothing() or Mockito itself is widely used testing framework. If you are working with Junit 4 then you can read the similar example Mockito’s doNothing() using Junit 4 .

Mockito ‘s doNothing() is used when you want to test void methods because void methods do not return anything so there is no way you can verify using assert. These void methods may be anywhere, for example, in service class, in dao class, etc.

Prerequisites

Eclipse 2020-06, Java at least 1.8, Junit 5, Gradle 6.5.1

How to configure Junit 5 for Java projects

Project Setup

Create gradle based project in Eclipse. The name of the project is java-junit-5-mockito-donothing .

Update the build.gradle script with the required dependencies as shown below:

This is just a simple class that holds object’s state.

A simple dao class that does some database activities but here I am doing nothing for this example.

Service Class

The service class that does the business logic. But for this example I have kept it simple.

Junit Class

Create Junit class to test our service class. Here we will see how to use  doNothing()  method from Junit 5’s Mockito framework.

We are using  doNothing()  method on void method only because void method does not return anything.

I am using @ExtendWith(...) instead of @RunWith(...) in Junit 5 test class.

Using Junit 5 how it is easy to use Mockito framework. You just need to use @Mock annotation to mock the object.

I am testing doNothing() both on dao and service class’ methods.

Testing doNothing()

Running the Junit class will give you the success results as shown below in the image:

java junit 5 mockito doNothing example

That’s all. Hope you got an idea how to use doNothing() method on void methods for testing using Junit 5.

Source Code

Thanks for reading.

Leave a Reply Cancel reply

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

Copyright © 2024 Roy Tutorials

Privacy | Terms & Conditions

JUnit 5 tutorial - Learn how to write unit tests

1.1. configuration for using junit 5, 1.2. how to define a test in junit, 1.3. example for developing a junit 5 test for another class, 1.4. junit test class naming conventions, 1.5. where should the test be located, 1.6. static imports and unit testing, 2.1. testing for exceptions, 2.2. testing multiple assertions (grouped assertions) with assertall, 2.3. defining timeouts in your tests, 2.4. how to disable tests, 3.1. using dynamic tests, 3.2. using parameterized tests, 4.1. nested tests, 4.2. test execution order, 4.3. using the @tempdir annotation to create temporary files and paths, 4.4. test suites, 5.1. project creation, 5.2. configure maven dependencies for junit 5, 5.3. package creation, 5.4. create a java class, 5.5. create a junit test, 5.6. run your test in eclipse, 5.7. fix the bug and re-run your tests, 5.8. review, 5.9. simplify your test code with @before each, 5.10. define a group check with assertall, 6.1. project creation, 6.2. update build.gradle file to use junit5, 6.3. create a java class, 6.4. create a junit test, 6.5. run your test in eclipse, 6.6. fix the bug and re-run your tests, 6.7. review, 6.8. simplify your test code with @before each, 6.9. define a group check with assertall, 7.1. create project and add junit5 dependencies, 7.2. create the data model used for testing, 7.3. write tests for the model and the services, 7.4. verify on command line, 7.5. add a long running method to your data service, 7.6. develop a test to constrain the execution time of the long running method, 8.1. create the data model used for testing, 8.2. write tests for the model and the services, 8.3. verify, 8.4. solution, 9.1. write tests checking for exceptions, 9.2. verify, 9.3. solution, 9.4. enable test only on certain platforms, 10.1. write tests, 10.2. solution, 10.3. run tests, 11.1. create class for testing, 11.2. write a dynamic test, 11.3. verify, 12.1. add dependency, 12.2. write a parameterized test, 12.3. verify, 12.4. add more options, 13.1. create class under test, 13.2. write tests, 14.1. add dependency to @inject, 14.2. create class under test, 14.3. solution, 15. exercise: create test reports, 16. exercise: clone the junit5 github repo and review tests, 17. overview of junit5 annotations, 18. conclusion, 19. junit resources.

This tutorial explains unit testing with JUnit with the JUnit 5 framework (JUnit Jupiter). It explains the creation of JUnit 5 tests with the Maven and Gradle build system. It demonstrates the usage of the Eclipse IDE for developing software tests with JUnit 5 but this tutorial is also valid for tools like Visual Code or IntelliJ.

Check out our Java Testing training including Instructional Videos

1. overview.

JUnit is a popular unit-testing framework in the Java ecosystem. JUnit 5 added many new features based on the Java 8 version of the language.

This guide gives an introduction into unit testing with the JUnit framework using JUnit 5. It focus on the usage of the framework.

For further information about testing with Java see:

What is software testing

Using Maven in the Eclipse IDE

Using the Eclipse IDE for creating and running JUnit test

Using Gradle in the Eclipse IDE

Mockito tutorial

JUnit 5 extensions

Hamcrest Tutorial

AssertJ Tutorial

JUnit 4 tutorial

To use JUnit 5 you have to make the libraries available for your test code. Jump to the section which is relevant to you, for example read the Maven part, if you are using Maven as build system.

== Configure Maven dependencies for JUnit 5

=== Steps required to configure Maven to use JUnit5

To use JUnit5 in an Maven project, you need to:

Configure to use Java 11 or higher, as this is required by JUnit5

Configure the maven-surefire-plugin and maven-failsafe-plugin to be at version 2.22.2 so that they can run JUnit5

Add dependencies to the JUnit5 API and engine for your test code

=== Configure Maven

Therefore you need to adjust your pom file, similar to the following:

Once you have done this, you can start using JUnit5 in your Maven project for writing unit tests.

=== Update Maven settings (in case you are using the Eclipse IDE)

Right-click your pom file, select Maven   Update Project and select your project. This triggers an update of your project settings and dependencies.

== Update build.gradle file to use JUnit5

To use JUnit 5 with the Gradle build system, ensure you use at least Gradle 6.0 to avoid already fixed issues.

Modify your build.gradle file to contain at least the following entries. Your build file may contain more dependencies.

If you are not using a build system and the JUnit library is not part of the classpath of your project during the creation of a new test, Eclipse prompts you to add it.

A JUnit test is a method contained in a class which is only used for testing. This is called a Test class . To mark a method as a test method, annotate it with the @Test annotation. This method executes the code under test.

The following code defines a minimal test class with one minimal test method.

You can use assert methods, provided by JUnit or another assert framework, to check an expected result versus the actual result. Such statement are called asserts or assert statements .

Assert statements typically allow to define messages which are shown if the test fails. You should provide here meaningful messages to make it easier for the user to identify and fix the problem. This is especially true if someone looks at the problem, who did not write the code under test or the test code.

The following example defines a Java class and defines software tests for it.

Assume you have the following class which you want to test.

A test class for the above class could look like the following.

The method annotated with @BeforeEach runs before each test
A method annotated with @Test defines a test method
@DisplayName can be used to define the name of the test which is displayed to the user
This is an assert statement which validates that expected and actual value is the same, if not the message at the end of the method is shown
@RepeatedTest defines that this test method will be executed multiple times, in this example 5 times

Build tools like Maven use a pattern to decide if a class is a test classes or not. The following is the list of classes Maven considers automatically during its build:

includes all of its subdirectories and all Java filenames that start with .
includes all of its subdirectories and all Java filenames that end with .
includes all of its subdirectories and all Java filenames that end with .
includes all of its subdirectories and all Java filenames that end with .

Therefore, it is common practice to use the Test or Tests suffix at the end of test classes names.

Typical, unit tests are created in a separate source folder to keep the test code separate from the real code. The standard convention from the Maven and Gradle build tools is to use:

src/main/java - for Java classes

src/test/java - for test classes

JUnit 5 allows to use static imports for its assertStatements to make the test code short and easy to read. Static imports are a Java feature that allows fields and methods defined in a class as public static to be used without specifying the class in which the field is defined.

JUnit assert statements are typically defined as public static to allow the developer to write short test statements. The following snippet demonstrates an assert statement with and without static imports.

2. Assertions and assumptions

JUnit 5 comes with multiple assert statements, which allows you to test your code under test. Simple assert statements like the following allow to check for true, false or equality. All of them are static methods from the org.junit.jupiter.api.Assertions.* package.

Assert statement Example

assertEquals

assertEquals(4, calculator.multiply(2, 2),"optional failure message");

assertTrue

assertTrue('a' < 'b', () → "optional failure message");

assertFalse

assertFalse('a' > 'b', () → "optional failure message");

assertNotNull

assertNotNull(yourObject, "optional failure message");

assertNull

assertNull(yourObject, "optional failure message");

Messages can be created via lambda expressions, to avoid the overhead in case the construction of the message is expensive.

Testing that certain exceptions are thrown are be done with the org.junit.jupiter.api.Assertions.expectThrows() assert statement. You define the expected Exception class and provide code that should throw the exception.

This lets you define which part of the test should throw the exception. The test will still fail if an exception is thrown outside of this scope.

If an assert fails in a test, JUnit will stop executing the test and additional asserts are not checked. In case you want to ensure that all asserts are checked you can assertAll .

In this grouped assertion all assertions are executed, even after a failure. The error messages get also grouped together.

If these tests fail, the result looks like the following:

If you want to ensure that a test fails, if it isn’t done in a certain amount of time you can use the assertTimeout() method. This assert fails the method if the timeout is exceeded.

If you want your tests to cancel after the timeout period is passed you can use the assertTimeoutPreemptively() method.

The @Disabled or @Disabled("Why disabled") annotation marks a test to be disabled. This is useful when the underlying code has been changed and the test case has not yet been adapted of if the test demonstrates an incorrect behavior in the code which has not yet been fixed. It is best practice to provide the optional description, why the test is disabled.

Alternatively you can use Assumptions.assumeFalse or Assumptions.assumeTrue to define a condition for test execution. Assumptions.assumeFalse marks the test as invalid, if its condition evaluates to true. Assumptions.assumeTrue evaluates the test as invalid if its condition evaluates to false. For example, the following disables a test on Linux:

This gives TestAbortedException which the test runners evaluate as skipped tests.

For example the following testMultiplyWithZero is skipped if executed on Linux.

You can also write an extension for @ExtendWith which defines conditions under which a test should run.

3. Dynamic and parameterized tests

JUnit 5 supports the creation of dynamic tests via code. You can also run tests with a set of different input values with parameterized tests.

Both approaches are described here.

Dynamic test methods are annotated with @TestFactory and allow you to create multiple tests of type DynamicTest with your code. They can return:

an Iterable

a Collection

JUnit 5 creates and runs all dynamic tests during test execution.

Methods annotated with @BeforeEach and @AfterEach are not called for dynamic tests. This means, that you can’t use thesm to reset the test object, if you change it’s state in the lambda expression for a dynamic test.

In the following example we define a method to return a Stream of DynamicTest instances.

Junit5 also supports parameterized tests. To use them you have to add the junit-jupiter-params package as a test dependencies.

If you are using Gradle:

For this example we use the @MethodSource annotation.

We give it the name of the function(s) we want it to call to get it’s test data. The function has to be static and must return either a Collection, an Iterator, a Stream or an Array. On execution the test method gets called once for every entry in the data source. In contrast to Dynamic Tests @BeforeEach and @AfterEach methods will be called for parameterized tests.

3.2.1. Data sources

The following table gives an overview of all possible test data sources for parameterized tests.

Table 1. Table Parameterized Tests Data Sources
Annotation Description
(ints = { 1, 2, 3 })

Lets you define an array of test values. Permissible types are , , , or .

(value = Months.class, names = {"JANUARY", "FEBRUARY"})

Lets you pass Enum constants as test class. With the optional attribute you can choose which constants should be used. Otherwise all attributes are used.

(names = "genTestData")

The result of the named method is passed as argument to the test.

({ "foo, 1", "'baz, qux', 3" }) void testMethod(String first, int second) {

Expects strings to be parsed as Csv. The delimiter is .

(MyArgumentsProvider.class)

Specifies a class that provides the test data. The referenced class has to implement the interface.

3.2.2. Argument conversion

JUnit tries to automatically convert the source strings to match the expected arguments of the test method.

If you need explicit conversion you can specify a converter with the @ConvertWith annotation. To define your own converter you have to implement the ArgumentConverter interface. In the following example we use the abstract SimpleArgumentConverter base class.

4. Additional information about JUnit 5 usage

The @Nested annotation can be used to annotate inner classes which also contain tests. This allows to group tests and have additional @BeforeEach method, and one @AfterEach methods. When you add nested test classes to our test class, the following rules must be followed:

All nested test classes must be non-static inner classes.

The nested test classes are annotated with @Nested annotation so that the runtime can recognize the nested test classes.

a nested test class can contain Test methods, one @BeforeEach method, and one @AfterEach method.

Because Java doesn’t allow static members in inner classes, a nested class cannot have additional @BeforeAll and @AfterAll methods. There is no limit for the depth of the class hierarchy.

JUnit runs test methods is a deterministic but unpreditable order (MethodSorters.DEFAULT). You can use the @TestMethodOrder on the class to control the execution order of the tests, via:

@TestMethodOrder(MethodOrderer.OrderAnnotation.class) - Allows to use the @Order(int) annotation on methods to define order

@TestMethodOrder(MethodOrderer.DisplayName.class) - runs test method in alphanumeric order of display name

@TestMethodOrder(MethodOrderer.MethodName.class) - runs test method in alphanumeric order of method name

Custom implementation - Implement your own MethodOrderer via the orderMethods method, which allows you to call context.getMethodDescriptors().sort(..)

The following demonstrates this with OrderAnnotation.class .

The @TempDir annotations allows to annotate non-private fields or method parameters in a test method of type Path or File. JUnit 5 has registered a `ParameterResolutionException for this annotation and will create temporary files and paths for the tests. It will also remove the temporary files are each test.

The 5.8 release of JUnit 5 is planned to have test suite support included.

See https://github.com/junit-team/junit5/pull/2416 for the work.

At this time of writing you can use the milestone release of 5.8.0-M1 to check this. See the dependencies here https://search.maven.org/artifact/org.junit.platform/junit-platform-suite-api/1.8.0-M1/jar

5. Exercise: Writing a JUnit 5 test with Maven and Eclipse in 5 mins

In this exercise you learn you to write a JUnit5 test using Maven and the Eclipse IDE.

Create a new Maven project with the following settings:

Group: com.vogella

Artifact: com.vogella.junit.first

Version: 0.0.1-SNAPSHOT

Packaging: jar

5.2.1. Steps required to configure Maven to use JUnit5

5.2.2. configure maven, 5.2.3. update maven settings (in case you are using the eclipse ide).

Create a package named com.vogella.junit.first in the src/main/java and src/main/test folder.

In the src folder, create the following class in the com.vogella.junit.first package.

Position the cursor on the MyClass in the Java editor and press Ctrl+1. Select that you want to create a new JUnit test from the list.

Create new test class

Alternatively you can right-click on your new class in the :_Project Explorer_ or view and select       .

In the following wizard ensure that the New JUnit Jupiter test flag is selected. The source folder should select the test directory.

Create new test class

Press the Next button and select the methods that you want to test.

Selecting the methods to test

Create a test with the following code.

Right-click on your new test class and select Run-As   JUnit Test .

Run JUnit test in Eclipse

The result of the tests are displayed in the JUnit view. In our example one test should be successful and one test should show an error. This error is indicated by a red bar.

Result of running a unit test

You discovered a bug in the tested code!

The test is failing, because our multiplier class is currently not working correctly. It does a division instead of multiplication. Fix the bug and re-run the test to get a green bar.

After a few minutes you should have created a new project, a new class and a new unit test. Congratulations! If you feel like it, lets improve the tests a bit and write one grouped test.

The initialization of MyClass happens in every test, move the initialization to a @BeforeEach method.

Define a new test method which checks both condition at the same time with assertAll statement. Change the condition to make both tests fail, run the test and ensure that both are executed.

junit80

Afterwards adjust the test so that both are successfully executed.

6. Exercise: Writing a JUnit 5 test with Gradle and Eclipse in 5 mins

In this exercise you learn you to write a JUnit5 test using the Gradle build system and the Eclipse IDE.

Create a new Gradle project with the following setting:

Name: com.vogella.junit.first

See Create a Grade project with Eclipse to learn how to create a Gradle project with Eclipse.

The wizard should also have create the package com.vogella.junit.first in the src/main/java and src/main/test folder. Remove the generated classes from it.

7. Exercise: Writing JUnit5 unit tests

In this exercise, you develop some JUnit 5 tests for a given data model. You already learned how to create projects with Maven or Gradle and how to add Junit5 to them.

To review this information see:

Create a Grade project with Eclipse

Adding JUnit to an project

The following description assumes that you are familiar with these steps and will not repeat them.

Create a new project called com.vogella.unittest either with Maven or with Gradle and update their settings to use JUnit5.

Create the com.vogella.unittest.model package and copy and paste the following classes on it.

Create the com.vogella.unittest.services package and copy and paste the following classes on it.

Create the following test class.

Solve the TODO and ensure that all tests can be successfully executed from your IDE. You may find issues in the DataService with these tests, fix them if you encounter them.

The following is a possible implementation of the tests:

You actually found errors in the DataService implementations, adjust the following method:

Verify that your code compiles and your test are running via the command line with:

mvn clean verify in case you are using Maven

./gradlew test in case you are using Gradle

Add a fake update method to your DataService which takes a long time to update the data and returns true on success.

Create a new test method in your DataServiceTest . Use the assertTimeout assert statement to ensure that this test does not run longer than 3 seconds.

8. Exercise: Develop unit tests for a regular expression utility method for email verification

Create the com.vogella.unittest.email package and copy and paste the following classes on it.

Fix all the failing test, unfortunately the test specification is not very good. Try to write reasonable tests which fit the method name.

Run your new test via the IDE. Verify that your code compiles and your test are running via the command line.

The following listing contains a possible implementation of the test.

9. Exercise: Testing exceptions and conditional enablement

We also want to check that exceptions with the correct error messages are thrown, if we call the class under test with incorrect data.

Fix the disabled tests and enable them. The name should give a good indication what you have to do test here.

You may discover that the data model does not behave a expected by the test, fix them in this case.

Run your update test via the IDE. Verify that your code compiles and your test are running via the command line with the mvn clean verify .

The test indicates that you need to update the TolkienCharacter constructor.

Write this test and adjust it so that is only runs on the operating system you are using.

10. Exercise: Writing nested tests to group tests for display

Create the following test.

Run the test from your IDE and review how the grouped tests are displayed.

11. Exercise: Testing multiple parameter

Create the com.vogella.unittest.converter package and copy and paste the following class on it.

Run your new test via the IDE and ensure that you have 6 tests running succesfull.y

Verify that your code compiles and your test are running via the command line either with ./gradlew test`or with the `mvn clean verify depending on your build system.

12. Exercise: Testing with multiple input parameter

Dynamic tests are included in the regular JUnit 5 library, which you already included. To use parameters in your tests, you have to add the junit-jupiter-params library.

If you are using Maven add the following dependency to junit-jupiter-params to your Maven pom file.

If you are using Gradle add the following to your build.gradle file

Review the following code:

Create a new test method in ConverterUtilTest which also uses a parameterized test.

Run your new test via the IDE.

convertertestresult10

Verify that your code compiles and your test are running via the command line with the ./gradlew test or mvn clean verify command based on your build system.

ParameterizedTest are very flexible in sense of their input. The following lists a few more. Add these to your test and run the tests again.

13. Exercise: Using the @TempDir annotation to create temporary files and paths

In this exercise you learn how to use the @TempDir annotation to let JUnit 5 create files and paths on request in your test and to automatically remove them after the test.

Create the following class

Using the @TempDir annotation, create unit which test named FileWriterTest for the following:

Ensure that the Path given to you by the @TempDir annotation if writable

Ensure that a appending to a file with FileWriter.appendFile which has not yet been created with FileWriter.createFile throws an exception

Ensure that you can write to the file once you created it

13.2.1. Solution

14. exercise: testing for annotations.

In this exercise you write test to check class under test for certain annotations.

If you have not yet done this, add a dependency to javax.inject.

t validates that the Servic === Write tests

Write a test that validates that the Service class only has one constructor annotated with @Inject .

The class has a `getConstructors method.

The Constructor has a method getAnnotation

Both Maven and Gradle allow to generate HTML report for unit tests.

Gradle creates these automatically, if you run the ./gradlew build command and with Maven you run the mvn clean verify surefire-report:report command.

Run this for your project and check the build folder for the generated test reports.

Open JUnit5 Github page in your browser and clone the repo.

Import the project into your favorite IDE and review some of the tests, e.g. the platform-tests contains a lot of useful tests.

The following table gives an overview of the most important annotations in JUnit 5 from the org.junit.jupiter.api package.

Table 2. Annotations
Annotation Description

Identifies a method as a test method.

Disables a test method with an option reason.

Executed before each test. Used to prepare the test environment, e.g., initialize the fields in the test class, configure the environment, etc.

Executed after each test. Used to cleanup the test environment, e.g., delete temporary data, restore defaults, cleanup expensive memory structures.

<Name> that will be displayed by the test runner. In contrast to method names the name can contain spaces to improve readability.

Similar to but repeats the test a <Number> of times

Annotates a static method which is executed once, before the start of all tests. It is used to perform time intensive activities, for example, to connect to a database. Methods marked with this annotation need to be defined as to work with JUnit.

Annotates a static method which is executed once, after all tests have been finished. It is used to perform clean-up activities, for example, to disconnect from a database. Methods annotated with this annotation need to be defined as to work with JUnit.

Annotates a method which is a Factory for creating dynamic tests

Lets you nest inner test classes to group your tests and to have additional @BeforeEach and @AfterEach methods.

Tags a test method, tests in JUnit 5 can be filtered by tag. E.g., run only tests tagged with "fast".

Lets you register an Extension class that adds functionality to the tests

JUnit 5 makes is easy to write software tests.

The implementation of all these examples and code snippets can be found over on Github . The Maven examples are located in JUnit with Maven and the Gradle examples are located in JUnit 5 with Gradle .

If you need more assistance we offer Online Training and Onsite training as well as consulting

See License for license information .

how to write the junit for void method

JUnit Homepage

JUnit 5 user guide

Software Testing Help

JUnit Tests: How To Write JUnit Test Cases With Examples

how to write the junit for void method

This JUnit Tests Tutorial will focus on how to Write JUnit Tests in Eclipse, Test Output, and JUnit 4 Test Case Example in Java Eclipse:

We will cover the following topics:

  • The navigational workflow of creating a test case in Eclipse.
  • How does an auto-created basic template of JUnit test case look like?
  • A couple of examples on JUnit 4 basic test cases and trying to interpret the code.
  • Simultaneously, we will also cover all about the resultant console window and how to save the failed tests along with their stack traces for future reference.

=> Take A Look At The JUnit Beginners Guide Here.

JUnit Tests

Table of Contents:

JUnit 4 Test – Basic Examples

Save failed tests and stacktraces, was this helpful, recommended reading, create junit tests in eclipse.

Let’s begin creating the JUnit test in Eclipse.

#1) Open Eclipse

#2) Create a Project folder through the navigation flow: File->New->Java Project . Another window opens up where the user needs to enter the Project folder name. The screenshot is given below.

#3) You may set the default workspace path by checking the checkbox Use default location or may uncheck it to set a different path. This will be the path where all your project files – your java class files, JUnit class files or TestNG class files would be stored along with its report, log files, and test data files if any.

#4) The JRE environment is also set by default. However, do check if the JRE configured is correct.

#5) Click the Finish button at the bottom of the dialog box.

Create a Project

#6) With this, the Project folder with the name gets added in the project explorer as shown below.

project explorer

#7) Now let us see how to add a new JUNIT Testcase into the project folder. Select Project folder => src folder => Right-click on the src folder => Select New => Junit Test Case.

Junit Test Case

#8) A window opens up, where you can enter the following:

  • Select the source folder path in the Source folder.
  • Enter the package name. If the package name is not entered, the files go under the default package that is usually not encouraged or in other words, not a good coding practice to follow.
  • Enter the JUnit class name.
  • There are few stub methods: setUpBeforeClass(), tearDownAfterClass(), setUp(), teardown(). In case, you need a ready template of these methods added, then you may check the respective checkbox.
  • Click the Finish button.

Create testcase

Below is the default template of the class file that gets generated:

default template of the class file

Let’s now begin with the creation of a basic JUnit 4 test.

Under the package demo. tests , we have created a JUnit test class file and have included a method test_JUnit() that verifies if the str1 variable and string passed in the condition are both equal. The comparison of the expected condition has been performed by the assertEquals() method which is a JUnit specific method.

We will discuss the method along with many other methods supported by JUnit that makes it worth using it later. Besides, also observe the @Test annotation added here. @Test defines the test case in a JUnit class file.

Similarly, you may have multiple test cases in one class file by having multiple methods in place each preceded by @Test annotation. We will also discuss all the annotations supported by JUnit i.e. both JUnit 4 and JUnit 5 in our subsequent tutorials.

The test is supposed to Pass on executing the below code snippet as both the expected and the actual string values match.

The result on console and JUnit Result Tab:

On executing the JUnit class, the console and JUnit result tab shows up,

  • The Console shows as below where a message reads as ‘This is the test case in this class’.
  • The JUnit result tab displays mainly the number of test cases run, number of errors and number of failures encountered i.e. Run: 1/1 (meaning 1 testcase out of 1 testcase ran), Errors: 0 (no errors found in the test case executed), Failures: 0(no test cases failed)
  • The time taken to finish the execution of the tests.
  • Displays a green bar if all the test cases are passed.
  • Just above the timestamp on the JUnit tab, you see different icons: The first icon shows ‘Next Failed Test’, the second icon shows ‘Previous Failed Test’, and the third icon with a blue and red cross helps you to filter out only failed tests. The icon next to this is to filter only the test cases that were skipped during execution.

different icons

Now, let’s make a slight update to the code such that the expected string value doesn’t match the actual. The test is supposed to Fail on executing the updated code snippet as both the expected and the actual string values do not match. In the screenshot below, you can see the updated code as well as the resultant tab.

Result on console and JUnit Result Tab:

On executing the JUnit class, the console and JUnit result tab shows up the below.

#1) The Console message and timestamp under the JUnit result tab display as it was in the earlier example.

#2) The difference with this change is in the JUnit results tab. The Failures count now shows 1, with a red bar implying that the testcase has failed. Given below is a screenshot for your reference.

JUnit results tab

#3) At the bottom of the Left panel, there is a ‘Failure Trace ’ tab that shows the reason why the testcase failed.

#4) When you click on the first line under the Failure Trace, a window that shows the deviation between the expected results and actual results very clearly opens up.

Screenshot of the deviation window is shown below:

the deviation window

  • On the failed test under the JUnit result view, navigate to the Failure Trace tab, right-click and select the option ‘Copy Failure List’.
  • You will be able to paste it in a notepad or word and save it for your future reference. The copy pasted content includes all the stack traces of this failed instance of the testcase along with the testcase name.

Save Failed Tests and Stacktraces

We covered how to create a JUnit test with an example of how does a basic JUnit test case looks like along with the know-how on the result of the test case both in situations when it fails or passes. Besides, we also learned that stack traces and the tests could be saved externally.

In our upcoming tutorial, we shall move on to Test Fixture where we will learn an approach towards setting certain precondition tests, the actual test methods, and certain postcondition tests.

  • JUnit Tutorial For Beginners - What Is JUnit Testing
  • What Is A JUnit Test Fixture: Tutorial With JUnit 4 Examples
  • JUnit Test Execution Order: Order Of Tests JUnit 4 Vs JUnit 5
  • JUnit Test Suite & Filtering Test Cases: JUnit 4 Vs JUnit 5
  • JUnit Ignore Test Case: JUnit 4 @Ignore Vs JUnit 5 @Disabled
  • JUnit 5 Nested Class: @Nested Tutorial With Examples
  • List Of JUnit Annotations: JUnit 4 Vs JUnit 5
  • JUnit Vs TestNG - What Are The Differences

Leave a Comment Cancel reply

Stack Exchange Network

Stack Exchange network consists of 183 Q&A communities including Stack Overflow , the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Q&A for work

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

Unit testing a void method

In order to fix a bug in an application, I modified a method named postLogin by adding a call to an existing method named getShoppingCart .

However, I'm not sure what the best way to write a unit test for postLogin is.

Use verify from Mockito to simply verify that the method was called.

Test the side effect of the method call by fetching the value of the user's shopping cart.

Is one approach better than the other?

  • unit-testing

A_B's user avatar

  • 1 whichever makes the test easier to understand, and keeps the code clean. If you are unsure of the test design, that COULD also be a sign that the code design is off. Make sure you are asking these questions: " WHY does adding that method call fix the bug? Is this the RIGHT way to fix this bug?" –  Caleb Commented Nov 25, 2017 at 20:06
  • 9 Unless your getShoppingCart() method has side-effects, you don't need to test that it's called. If it does have side effects, you should really change its name because getXXX() methods conventionally should be idempotent. –  Jules Commented Nov 26, 2017 at 2:41
  • @Jules getNextValue ? Arguably, someone could say "Don't call it a getter; change the name to nextValue ", but I have seen getNext used before. Perhaps a better example would be an object representing an electron; what happens when I call getPosition ? Or worse, getPosition(); getVelocity(); –  Aaron Commented Nov 30, 2017 at 22:14

5 Answers 5

I would usually prefer method 2.

Why? Because, you want postLogin to change some state of your system, but how it accomplishes this (and which methods it calls internally for this) is merely an implementation detail, nothing your unit test should make any assumptions about. So better make your test just verifying the final state.

Doc Brown's user avatar

I would change getShoppingCart to something like initializeShoppingCart, the purpose of the method should be clear to whoever reads it without the need to check what the method does and side effects like this can cause some surprising behavior for users of the method.

If getShoppingCart is in another class and it's already unit tested I would use approach 1 - no need to test again what's already tested. In this case we are sure that getShoppingCart works properly and we only want to assure that it's called from postLogin so if someone in the future removes this call the test will fail.

If getShoppingCart is a private method which can not be tested by itself, then I would use approach 2, to make sure that when postLogin is called the desired functionality of getShoppingCart is performed as expected.

Nastya S's user avatar

When testing a function call (void or not) that has a side effect, it’s most complete to test that the side effect not only occurs, but to check that the side effect (system output or or state change) is the one desired.

hotpaw2's user avatar

  • 1 While this is true, it is also worth considering that the details of the side effect that occurs could be part of the internal state of some other module, and that by checking those details you'd be coupling your test to not only the module that it is testing but also that other module, which could lead to brittle tests if those details are likely to change. Mocking the interface between modules helps prevent this problem. –  Jules Commented Nov 26, 2017 at 2:44

I won't discuss your design, but in your case I would go for the first approach because unit test is for testing what methods do technically regardless of their job in the domain, that is, what your method postLogin does? Technically it calls getShoppingCard so you have to test that is really is calling getShoppingCard , I would also create another test for getShoppingCard to test what it does and if it has side effects I will check it inside that new test.

La VloZ Merrill's user avatar

You have a bug in postLogin. So the first thing you should do is create a unit test which upon calling postLogin without the expected set of information will "fail".

From the above idea, another alternative from the 2 proposed is to inject the information about the shopping cart as a parameter. If you don't have the correct information, you throw an unchecked exception. This will make it clear that without the correct details, your method is doomed.

This will require a little change where the client calling the postLogin right now is required to also pass the shopping cart info. To me this is still coherent now that you see they are coupled. This coupling will be done by the caller.

Then you wouldn't even need to test getShoppingCart inside postLogin because the real method under test is postLogin. It is the one that has the bug and the only one that requires proper fix and validation. With the injected dependency, you will be able to test it easily under different condition and confirm that no error is thrown.

gumol's user avatar

Not the answer you're looking for? Browse other questions tagged java unit-testing testing junit or ask your own question .

  • Featured on Meta
  • Upcoming sign-up experiments related to tags

Hot Network Questions

  • How can a landlord receive rent in cash using western union
  • Why is polling data for Northern Ireland so differently displayed on national polling sites?
  • Why does Balarama drink wine?
  • What is the meaning of the angle bracket syntax in `apt depends`?
  • Idiom for a situation where a problem has two simultaneous but unrelated causes?
  • How Does the Blockchain Recognize Locked UTXOs in a PSBT if the PSBT Isn't Stored On-Chain?
  • What stops a plane from rolling when the ailerons are returned to their neutral position?
  • Brakes not going back on their own
  • Approach to software testing with docker
  • What's the meaning of "nai gar"?
  • Stiff differential equation
  • Should mail addresses for logins be stored hashed to minimize impact of data loss?
  • Can a unique position be deduced if pieces are replaced by checkers (can see piece color but not type)
  • "All due respect to jazz." - Does this mean the speaker likes it or dislikes it?
  • Cleaning chain a few links at a time
  • Synthesis of racemic nicotine
  • What is the best way to set a class value to a variable in Python if it exists in a dictionary?
  • Reconstructing Euro results
  • Diagnosing tripped breaker on the dishwasher circuit?
  • In an interview how to ask about access to internal job postings?
  • Old book about a man who finds an abandoned house with a portal to another world
  • Why depreciation is considered a cost to own a car?
  • How can I take apart a bookshelf?
  • A 90s (maybe) made-for-TV movie (maybe) about a group of trainees on a spaceship. There is some kind of emergency and all experienced officers die

how to write the junit for void method

Javatpoint Logo

JUnit Tutorial

JavaTpoint

JUnit tutorial provides basic and advanced concepts of with examples. Our junit tutorial is designed for beginners and professionals.

It is an for java programmers. The java programmer can create test cases and test his/her own code.

It is one of the unit testing framework. Current version is junit 4.

To perform unit testing, we need to create test cases. The is a code which ensures that the program logic works as expected.

The package contains many interfaces and classes for junit testing such as Assert, Test, Before, After etc.

There are two ways to perform unit testing: 1) manual testing 2) automated testing.

If you execute the test cases manually without any tool support, it is known as manual testing. It is time consuming and less reliable.

If you execute the test cases by tool support, it is known as automated testing. It is fast and more reliable.

The Junit 4.x framework is annotation based, so let's see the annotations that can be used while writing the test cases.

annotation specifies that method is the test method.

annotation specifies that method will be failed if it takes longer than 1000 milliseconds (1 second).

annotation specifies that method will be invoked only once, before starting all the tests.

annotation specifies that method will be invoked before each test.

annotation specifies that method will be invoked after each test.

annotation specifies that method will be invoked only once, after finishing all the tests.

The org.junit.Assert class provides methods to assert the program logic.

The common methods of Assert class are as follows:

: checks that two primitives/objects are equal. It is overloaded. : checks that a condition is true. : checks that a condition is false. : checks that object is null. : checks that object is not null.

You need to load and files.

Let's see the directory structure of this example.

Let's write the logic to find the maximum number for an array.

Here, we are using JUnit 4, so there is no need to inherit TestCase class. The main testing code is written in the testFindMax() method. But we can also perform some task before and after each test, as you can see in the given program.

To run this example, . Assertion Error

Let's see the output displayed in eclipse IDE.

As you can see, program logic to find the maximum number for the given array is not correct because it doesn't return -1 in case of negative values. The correct program logic is given below:

If you run the junit program again, you will see the following output.

before class before test case find max after before test case cube after before test case reverse word after after class



Youtube

  • Send your Feedback to [email protected]

Help Others, Please Share

facebook

Learn Latest Tutorials

Splunk tutorial

Transact-SQL

Tumblr tutorial

Reinforcement Learning

R Programming tutorial

R Programming

RxJS tutorial

React Native

Python Design Patterns

Python Design Patterns

Python Pillow tutorial

Python Pillow

Python Turtle tutorial

Python Turtle

Keras tutorial

Preparation

Aptitude

Verbal Ability

Interview Questions

Interview Questions

Company Interview Questions

Company Questions

Trending Technologies

Artificial Intelligence

Artificial Intelligence

AWS Tutorial

Cloud Computing

Hadoop tutorial

Data Science

Angular 7 Tutorial

Machine Learning

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures

DAA tutorial

Operating System

Computer Network tutorial

Computer Network

Compiler Design tutorial

Compiler Design

Computer Organization and Architecture

Computer Organization

Discrete Mathematics Tutorial

Discrete Mathematics

Ethical Hacking

Ethical Hacking

Computer Graphics Tutorial

Computer Graphics

Software Engineering

Software Engineering

html tutorial

Web Technology

Cyber Security tutorial

Cyber Security

Automata Tutorial

C Programming

C++ tutorial

Control System

Data Mining Tutorial

Data Mining

Data Warehouse Tutorial

Data Warehouse

RSS Feed

Guide to JUnit 5 Parameterized Tests

Last updated: June 27, 2024

how to write the junit for void method

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema .

The way it does all of that is by using a design model , a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

>> Take a look at DBSchema

Azure Spring Apps is a fully managed service from Microsoft (built in collaboration with VMware), focused on building and deploying Spring Boot applications on Azure Cloud without worrying about Kubernetes.

The Enterprise plan comes with some interesting features, such as commercial Spring runtime support, a 99.95% SLA and some deep discounts (up to 47%) when you are ready for production.

>> Learn more and deploy your first Spring Boot app to Azure.

And, you can participate in a very quick (1 minute) paid user research from the Java on Azure product team.

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only , so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server's performance, with most of the profiling work done separately - so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server , hit the record button, and you'll have results within minutes:

>> Try out the Profiler

A quick guide to materially improve your tests with Junit 5:

Do JSON right with Jackson

Download the E-book

Get the most out of the Apache HTTP Client

Get Started with Apache Maven:

Working on getting your persistence layer right with Spring?

Explore the eBook

Building a REST API with Spring?

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> REST With Spring (new)

Get started with Spring and Spring Boot, through the reference Learn Spring course:

>> LEARN SPRING

Get non-trivial analysis (and trivial, too!) suggested right inside your IDE or Git platform so you can code smart, create more value, and stay confident when you push.

Get CodiumAI for free and become part of a community of over 280,000 developers who are already experiencing improved and quicker coding.

Write code that works the way you meant it to:

>> CodiumAI. Meaningful Code Tests for Busy Devs

Looking for the ideal Linux distro for running modern Spring apps in the cloud?

Meet Alpaquita Linux : lightweight, secure, and powerful enough to handle heavy workloads.

This distro is specifically designed for running Java apps . It builds upon Alpine and features significant enhancements to excel in high-density container environments while meeting enterprise-grade security standards.

Specifically, the container image size is ~30% smaller than standard options, and it consumes up to 30% less RAM:

>> Try Alpaquita Containers now.

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth , to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project .

You can explore the course here:

>> Learn Spring Security

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot .

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Get started with Spring Boot and with core Spring, through the Learn Spring course:

1. Overview

JUnit 5 , the next generation of JUnit, facilitates writing developer tests with shiny new features.

One such feature is p arameterized tests . This feature enables us to execute a single test method multiple times with different parameters.

In this tutorial, we’re going to explore parameterized tests in depth, so let’s get started.

Further reading:

A guide to junit 5, using springjunit4classrunner with parameterized, introduction to junitparams, 2.  dependencies.

In order to use JUnit 5 parameterized tests, we need to import the  junit-jupiter-params artifact from JUnit Platform. That means, when using Maven, we’ll add the following to our pom.xml :

Also, when using Gradle, we’ll specify it a little differently:

3.  First Impression

Let’s say we have an existing utility function, and we’d like to be confident about its behavior:

Parameterized tests are like other tests except that we add the  @ParameterizedTest  annotation:

JUnit 5 test runner executes this above test — and consequently, the isOdd  method — six times. And each time, it assigns a different value from the @ValueSource array to the  number method parameter.

So, this example shows us two things we need for a parameterized test:

  • a source of arguments , in this case, an int array
  • a way to access them , in this case, the  number parameter

There is still another aspect not evident with this example, so we’ll keep looking.

4.  Argument Sources

As we should know by now, a parameterized test executes the same test multiple times with different arguments.

And we can hopefully do more than just numbers, so let’s explore.

4.1. Simple Values

With the  @ValueSource  annotation, we can pass an array of literal values to the test method.

Suppose we’re going to test our simple isBlank  method:

We expect from this method to return true for null for blank strings. So, we can write a parameterized test to assert this behavior:

As we can see, JUnit will run this test two times and each time assigns one argument from the array to the method parameter.

One of the limitations of value sources is that they only support these types:

  • short (with the  shorts attribute)
  • byte ( bytes attribute)
  • int ( ints attribute)
  • long ( longs attribute)
  • float ( floats attribute)
  • double ( doubles attribute)
  • char ( chars attribute)
  • java.lang.String ( strings attribute)
  • java.lang.Class ( classes attribute)

Also, we can only pass one argument to the test method each time.

Before going any further, note that we didn’t pass null as an argument. That’s another limitation — we can’t pass null  through a  @ValueSource , even for String and Class .

4.2. Null and Empty Values

As of JUnit 5.4, we can pass a single  null  value to a parameterized test method using  @NullSource :

Since primitive data types can’t accept  null  values, we can’t use the  @NullSource  for primitive arguments.

Quite similarly, we can pass empty values using the  @EmptySource  annotation:

@EmptySource  passes a single empty argument to the annotated method.

For String arguments, the passed value would be as simple as an empty String . Moreover, this parameter source can provide empty values for Collection types and arrays.

In order to pass both  null  and empty values, we can use the composed  @NullAndEmptySource  annotation:

As with the @EmptySource , the composed annotation works for  String s,  Collection s, and arrays .

To pass a few more empty string variations to the parameterized test, we can combine  @ValueSource , @NullSource , and @EmptySource  together :

In order to run a test with different values from an enumeration, we can use the @EnumSource annotation.

For example, we can assert that all month numbers are between 1 and 12:

Or, we can filter out a few months by using the  names  attribute.

We could also assert the fact that April, September, June and November are 30 days long:

By default, the  names will only keep the matched enum values.

We can turn this around by setting the  mode attribute to EXCLUDE :

In addition to literal strings, we can pass a regular expression to the names attribute:

Quite similar to  @ValueSource , @EnumSource  is only applicable when we’re going to pass just one argument per test execution.

4.4. CSV Literals

Suppose we’re going to make sure that the toUpperCase() method from  String generates the expected uppercase value. @ValueSource  won’t be enough.

To write a parameterized test for such scenarios, we have to

  • Pass an  input value  and  an  expected value to the test method
  • Compute the actual result with those input values
  • Assert  the actual value with the expected value

So, we need argument sources capable of passing multiple arguments.

The @CsvSource is one of those sources:

The @CsvSource accepts an array of comma-separated values, and each array entry corresponds to a line in a CSV file.

This source takes one array entry each time, splits it by comma and passes each array to the annotated test method as separate parameters.

By default, the comma is the column separator, but we can customize it using the delimiter attribute:

Now it’s a colon-separated value, so still a CSV.

4.5. CSV Files

Instead of passing the CSV values inside the code, we can refer to an actual CSV file.

For example, we could use a CSV file like this:

We can load the CSV file and ignore the header column with  @CsvFileSource :

The  resources  attribute represents the CSV file resources on the classpath to read. And, we can pass multiple files to it.

The  numLinesToSkip  attribute represents the number of lines to skip when reading the CSV files.  By default,  @CsvFileSource  does not skip any lines, but this feature is usually useful for skipping the header lines  like we did here.

Just like the simple  @CsvSource , the delimiter is customizable with the  delimiter  attribute.

In addition to the column separator, we have these capabilities:

  • The line separator can be customized using the  lineSeparator attribute — a newline is the default value.
  • The file encoding is customizable using the encoding attribute — UTF-8 is the default value.

4.6. Method

The argument sources we’ve covered so far are somewhat simple and share one limitation. It’s hard or impossible to pass complex objects using them.

One approach to providing more complex arguments is to use a method as an argument source.

Let’s test the  isBlank  method with a  @MethodSource :

The name we supply to  @MethodSource needs to match an existing method.

So, let’s next write provideStringsForIsBlank , a  static  method that returns a Stream  of Argument s :

Here we’re literally returning a stream of arguments, but it’s not a strict requirement. For example, we can return any other collection-like interfaces like  List.  

If we’re going to provide just one argument per test invocation, then it’s not necessary to use the  Arguments  abstraction:

When we don’t provide a name for the  @MethodSource , JUnit will search for a source method with the same name as the test method.

Sometimes, it’s useful to share arguments between different test classes. In these cases, we can refer to a source method outside of the current class by its fully qualified name:

Using the  FQN#methodName format, we can refer to an external static method.

Using a method as the argument source proved to be a useful way to supply the test data. Consequently, starting with JUnit 5.11, we can now use a similar feature with static fields, through the experimental annotation @FieldSource :

As we can see, the annotation points to a static field referencing the test data, which can be represented as a Collection , an Iterable , an object array, or a Supplier< Stream>. After that, the parameterized test will be executed for each test input. Similar to @MethodSource , if the name of the static field matches the name of the test, the value of the annotation can be omitted :

4.8. Custom Argument Provider

Another advanced approach to pass test arguments is to use a custom implementation of an interface called  ArgumentsProvider :

Then we can annotate our test with the  @ArgumentsSource  annotation to use this custom provider:

Let’s make the custom provider a more pleasant API to use with a custom annotation.

4.9. Custom Annotation

Suppose we want to load the test arguments from a static variable:

Actually, JUnit 5 does not provide this.  However, we can roll our own solution.

First, we can create an annotation:

Then we need to somehow consume the annotation details and provide test arguments. JUnit 5 provides two abstractions to achieve those:

  • AnnotationConsumer  to consume the annotation details
  • ArgumentsProvider  to provide test arguments

So, we next need to make the  VariableArgumentsProvider  class read from the specified static variable and return its value as test arguments:

And it works like a charm.

5. Repeatable Argument Source Annotations

In the previous section, we used various annotations to supply arguments for our parameterized tests. Starting with JUnit version 5.11, most of these annotations were improved and became repeatable. As a result, we can annotate a parameterized test multiple times with the same argument source annotation .

For example, we can use @MethodSource twice to execute the test with all the elements supplied by two different methods:

As we can see, this can be a convenient way of running the test with data coming from different sources. Here are all the argument source annotations supporting this feature:

  • @ValueSource
  • @EnumSource
  • @MethodSource
  • @FieldSource
  • @CsvFileSource
  • @ArgumentsSource

6. Argument Conversion

Now we know how to use various argument source annotations to supply primitive test data to our tests. Argument converters are a convenient way of mapping the primitive arguments of a parameterized test to more complex data structures .

6.1. Implicit Conversion

Let’s re-write one of those  @EnumTest s with a @ CsvSource :

This seems like it shouldn’t work, but it somehow does.

JUnit 5 converts the String  arguments to the specified enum type. To support use cases like this, JUnit Jupiter provides a number of built-in implicit type converters.

The conversion process depends on the declared type of each method parameter. The implicit conversion can convert the  String instances to types such as the following:

  • LocalDate , LocalTime , LocalDateTime , Year , Month , etc.
  • File  and  Path
  • URL  and  URI
  • Enum  subclasses

6.2. Explicit Conversion

We sometimes need to provide a custom and explicit converter for arguments.

Suppose we want to convert strings with the  yyyy/mm/dd   format to  LocalDate instances.

First, we need to implement the ArgumentConverter interface:

Then we should refer to the converter via the  @ConvertWith  annotation:

7. Argument Accessor

By default, each argument provided to a parameterized test corresponds to a single method parameter. Consequently, when passing a handful of arguments via an argument source, the test method signature gets very large and messy.

One approach to address this issue is to encapsulate all passed arguments into an instance of  ArgumentsAccessor  and retrieve arguments by index and type.

Let’s consider our Person class:

To test the fullName() method, we’ll pass four arguments:  firstName , middleName , lastName , and the  expected fullName . We can use the ArgumentsAccessor  to retrieve the test arguments instead of declaring them as method parameters:

Here, we’re encapsulating all passed arguments into an  ArgumentsAccessor  instance and then, in the test method body, retrieving each passed argument with its index. In addition to just being an accessor, type conversion is supported through  get* methods:

  • getString(index)  retrieves an element at a specific index and converts it to  String — the same is true for primitive types.
  • get(index)  simply retrieves an element at a specific index as an  Object .
  • get(index, type)  retrieves an element at a specific index and converts it to the given  type .

8. Argument Aggregator

Using the  ArgumentsAccessor  abstraction directly may make the test code less readable or reusable. In order to address these issues, we can write a custom and reusable aggregator.

To do that, we implement the  ArgumentsAggregator  interface:

And then we reference it via the  @AggregateWith  annotation:

The  PersonAggregator  takes the last three arguments and instantiates a  Person  class out of them.

9. Customizing Display Names

By default, the display name for a parameterized test contains an invocation index along with a  String  representation of all passed arguments:

However, we can customize this display via the name attribute of the  @ParameterizedTest  annotation:

April is 30 days long surely is a more readable display name:

The following placeholders are available when customizing the display name:

  • {index}  will be replaced with the invocation index. Simply put, the invocation index for the first execution is 1, for the second is 2, and so on.
  • {arguments}  is a placeholder for the complete, comma-separated list of arguments.
  • {0}, {1}, .. . are placeholders for individual arguments.

10. Conclusion

In this article, we explored the nuts and bolts of parameterized tests in JUnit 5.

We learned that parameterized tests are different from normal tests in two aspects: they’re annotated with the  @ParameterizedTest , and they need a source for their declared arguments.

Also, by now, we should know that JUnit provides some facilities to convert the arguments to custom target types or to customize the test names.

As usual, the sample code is available over on GitHub .

Just published a new writeup on how to run a standard Java/Boot application as a Docker container, using the Liberica JDK on top of Alpaquita Linux:

>> Spring Boot Application on Liberica Runtime Container.

Slow MySQL query performance is all too common. Of course it is.

The Jet Profiler was built entirely for MySQL , so it's fine-tuned for it and does advanced everything with relaly minimal impact and no server changes.

Explore the secure, reliable, and high-performance Test Execution Cloud built for scale. Right in your IDE:

Basically, write code that works the way you meant it to.

Build your API with SPRING - book cover

JMU

  • Download the following files: GiftCard.java to an appropriate directory/folder (e.g., the course downloads directory/folder). In most browsers/OSs, the easiest way to do this is by right-clicking/control-clicking on each of the links above and then selecting Save as... or Save link as... .
  • If you don't already have one from earlier in the semester, create a directory/folder named skills .
  • Outside of VSCode, copy the file GiftCard.java into that directory.
  • Start VSCode and Open GiftCard.java .
  • Create an empty JUnit test named GiftCardTest.java in the default package by right-clicking on the directory/folder, pulling down to New File... , and entering the file name in the textfield.
  • Copy the following code into GiftCardTest.java , after the declaration of the class. @Test public void getIssuingStoreTest() { double balance; GiftCard card; int issuingStore; issuingStore = 1337; balance = 100.00; card = new GiftCard(issuingStore, balance); assertEquals(issuingStore, card.getIssuingStore(), "getIssuingStore()"); }

How many tests are in the test suite GiftCardTest ?

where description is a human-readable String describing the test, expected is the expected result, and actual is the result of actually running the code being tested.

How would you call this method and pass it the String "getIssuingStore()" , the int issuingStore , and the int returned by the card object's getIssuingStore() method?

This feature should be used sparingly because it makes code very difficult to read. In this case, writing Assert.assertEquals() seems redundant, so people frequently use a static import .

testing.png

In fact, JUnit has a class (called org.junit.runner.JUnitCore with a main() method and that class is what is being executed. It then calls the various tests in GiftCardTest . The class with the main() method is being hidden from us by VSCode to make our lives easier.

Now what happens?

Note: You may have to scroll the test results view are to see the whole message.

In the summary on the right side of the test results view, the same information is presented in condensed form.

  • Before you forget, correct the fault in the getIssuingStore() method.

where tolerance determines how close two double values have to be in order to be considered "approximately equal".

Add a test named getBalanceTest() that includes a call to assertEquals() that can be used to test the getBalance() method in the card class (with a tolerance of 0.001 ).

Suppose, for example, you have two @Test -annotated methods, one with 99 assertions and the other with 1. Whether 1 of the 99 assertions fails or 98 out of the 99 assertions fails, JUnit will report that you failed one of two tests (i.e., 50% of the tests).

So, unless you have a good reason to do so, you should not include multiple tests inside of an @Test-annotated method.

Using JUnit terminology, add a test named deductTest_Balance() to your test suite that can be used to test the deduct() method in the GiftCard class. Note: Be careful, the variables that are declared in the getIssuingStore() method are local.

  • Execute the entire test suite.
  • There is a library called JaCoCo that provides coverage metrics for Java tests. Read the course "Help" page about using EclEmma .

watch.png

Why is the coverage of GiftCardTest.java uninteresting/unimportant?

  • Run the entire test suite.
  • The easiest (though not the most sophisticated) way to test for exceptions is to use include a try - catch statement in the test. For example, add the following test to your test suite. @Test public void constructorTest_IncorrectBalance() { try { new GiftCard(1, -100.00); fail("Constructor, Negative Balance: Should have thrown an IllegalArgumentException"); } catch (IllegalArgumentException iae) { // This is expected } }

Copyright 2024

Java Code Geeks

A Guide to Interfaces and Abstract Classes in Java

Photo of Eleftheria Drosopoulou

Java, a powerhouse programming language, offers a variety of tools to write clean, maintainable, and reusable code. Two of these essential tools are interfaces and abstract classes. While both promote abstraction, a core concept in object-oriented programming, they serve distinct purposes:

  • Interfaces define the “what” – they specify the behavior (methods) a class must implement, but not the “how” (implementation details).
  • Abstract classes provide a blueprint – they can define both behavior (methods) and a partial implementation, allowing subclasses to inherit and customize specific functionality.

Understanding the subtle differences between interfaces and abstract classes is crucial for writing well-structured and efficient Java code. This guide will unveil their functionalities, guiding you on when to choose one over the other in your development journey.

1. Interfaces and Abstract Classes in Java

In the realm of object-oriented programming (OOP), abstraction reigns supreme as a core concept for building robust and reusable code. Imagine a world where you don’t need to worry about the intricate details of how things work, but rather focus on what they do. Abstraction allows you to achieve just that.

Abstraction in Action

In the real world, you don’t need to understand the complex mechanics of an engine to drive. You simply interact with the steering wheel, brakes, and accelerator – functionalities provided by the car. Similarly, in OOP, abstraction allows you to define the functionalities (methods) that a class should provide without delving into the implementation details.

Enter Interfaces and Abstract Classes

Here’s where interfaces and abstract classes step in as powerful tools to promote abstraction in Java:

  • Interfaces: These act as contracts, specifying the behavior (methods) a class must implement. They define the “what” – what functionalities a class must offer – but leave the “how” (implementation details) up to the class itself. This promotes loose coupling, meaning classes only rely on the defined behavior, not the specific implementation.
  • Abstract Classes: These provide a blueprint for related classes. They can define both behavior (methods) and a partial implementation. Think of them as pre-written code that subclasses can inherit and customize. Abstract classes offer the “what” (methods) and a starting point for the “how” (partial implementation), allowing subclasses to fill in the gaps.

The Key Distinction

The crucial difference lies in the level of detail they provide:

  • Interfaces: Focus solely on the “what” – the behavior a class must exhibit.
  • Abstract Classes: Offer a blueprint with both “what” (methods) and a partial “how” (some implementation).

2. Interfaces in Java

In the world of Java programming, interfaces are powerful tools that champion abstraction. They act as contracts, defining the behavior (methods) that a class must adhere to, without dictating how those methods are implemented. Imagine them as blueprints outlining the functionalities a class must provide, leaving the specific implementation details to the class itself.

Benefits of Using Interfaces:

  • Loose Coupling: Interfaces promote loose coupling between classes. Classes only rely on the defined behavior (methods) specified in the interface, not the specific implementation details of those methods in another class. This makes your code more flexible and adaptable. Changes to the implementation of a method within a class won’t break other classes that rely on the interface, as long as the overall behavior remains consistent.
  • Code Reusability: By implementing the same interface, multiple unrelated classes can provide similar functionalities. This promotes code reusability, as you can write code that works with any class that implements the interface, regardless of its specific implementation details.
  • Polymorphism: Interfaces are the foundation for achieving polymorphism in Java. Polymorphism allows different classes to respond to the same method call in unique ways. Since all classes implementing an interface must define the same methods, you can create variables that hold references to objects of different classes, yet still call the methods defined in the interface. The specific implementation of the method that gets called depends on the actual object type at runtime.

Interface in Action: The Drawable Example

Let’s illustrate how interfaces work with a simple example:

In this example, the Drawable interface defines a single method draw() . The Circle and Square classes both implement the Drawable interface, but their implementations of the draw() method differ. The main method demonstrates the power of polymorphism. The drawable variable can hold references to both Circle and Square objects, and when you call draw() , the specific implementation defined by the actual object type gets executed.

3. Abstract Classes in Java

Abstract classes in Java act as a middle ground between the theoretical world of interfaces and the concrete realm of regular classes. They offer a blueprint for related classes, providing a foundation for code reuse and consistency. Imagine them as partially written code templates that subclasses can inherit and customize.

Benefits of Using Abstract Classes:

  • Base Class for Subclasses: Abstract classes serve as a base class for subclasses. They can define common properties and methods that all subclasses inherit. This promotes code reuse and reduces redundancy, as you don’t need to write the same code in every subclass.
  • Abstract Methods: Abstract classes have the power to define abstract methods. These methods lack an implementation within the abstract class itself. Subclasses are then obligated to implement these abstract methods to provide their own specific functionality. This enforces a certain level of consistency across subclasses, ensuring they all fulfill the required behavior.
  • Default Implementations: While abstract methods require implementation by subclasses, abstract classes can also offer default implementations for common functionality. This provides a starting point for subclasses, allowing them to override the default implementation if needed, or simply use it as is.

Abstract Class in Action: The Shape Example

Here’s an example of an abstract class and its subclasses:

In this example, the Shape class is abstract. It defines a common property ( color ) and an abstract method getArea() . Both Circle and Square inherit from Shape , gaining access to the color property and the default constructor to set it. They are then forced to implement the abstract method getArea() to provide their specific area calculation logic.

4. Choosing Between Interfaces and Abstract Classes

Now that you’ve explored the strengths of both interfaces and abstract classes, it’s time to understand which tool is best suited for your specific needs:

Use Interfaces When:

  • Defining Behavior Without Implementation: If your focus is solely on specifying the functionalities (methods) a class must provide, without dictating how those methods are implemented, interfaces are the way to go. They promote loose coupling and reusability, as unrelated classes can implement the same interface to offer similar behavior.
  • Promoting Loose Coupling and Reusability: Interfaces excel at decoupling classes from implementation details. This allows for greater flexibility and code reuse. Multiple classes can implement the same interface, even if they are not directly related, as long as they provide the required functionalities.

Use Abstract Classes When:

  • Providing a Blueprint with Partial Implementation: When you want to define a base class for related classes, offering a common foundation and promoting code reuse, abstract classes are your choice. They can provide a blueprint with pre-written code (methods) and properties that subclasses can inherit.
  • Enforcing Common Behavior: Abstract classes allow you to define abstract methods, which subclasses must implement. This enforces a certain level of consistency across related classes, ensuring they all fulfill the required behavior defined by the abstract methods.
  • Offering Default Implementations: While abstract methods require implementation by subclasses, abstract classes can also offer default implementations for common functionality. This provides a starting point for subclasses, allowing them to leverage the existing implementation or override it for specific needs.

5. Wrapping Up

Interfaces and abstract classes are your partners in building organized Java code. Interfaces define what a class does (methods) without how it does it. This keeps things flexible and reusable. Abstract classes provide a blueprint for related classes, offering a starting point (methods and properties) that subclasses can customize.

how to write the junit for void method

We will contact you soon.

Photo of Eleftheria Drosopoulou

Eleftheria Drosopoulou

Related articles.

how to write the junit for void method

Java 8 Streams – Group By Multiple Fields with Collectors.groupingBy()

Java program to calculate average using arrays, 150 java interview questions and answers – the ultimate list (pdf download & video), java 8 streams filter with multiple conditions examples, java arraylist insert/replace at index, switch as an expression in java with lambda-like syntax, 13 best java decompilers for download and online use for java developers, how to format/parse dates with localdatetime in java 8 – example tutorial.

guest

This site uses Akismet to reduce spam. Learn how your comment data is processed .

  • 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.

How to use class member variables inside Junit-Mockito tests

How can I pass myErrorServiceList when calling processErrorServiceList() so that both branches of the code are covered by a test case?

  • spring-boot

President James K. Polk's user avatar

  • 1 What did you try that didn't work? –  daniu Commented Jun 21 at 12:35
  • 1 Have you tried a setter, even if you are using it only internally? –  N Sarj Commented Jun 21 at 13:06
  • How can I write junit test case that bypass (CollectionUtils.NotEmplty(myErrorServiceList)) , currently I am using , when( (CollectionUtils.NotEmplty(any())).thenreturn(true), but this not works and throwing Mockito exception –  Henry Passion Commented Jun 22 at 5:39
  • 1 a) redesign your class to be testable b) move method out of class and make public static , so it can be tested independent of class for any kind of list c) use reflection to assign the field d) call your complex methods and have your list initialized. And honestly, I wouldn't test that method separately, it looks like a private implementation detail and should be covered by other tests that perform actual validation of important business logic. –  knittl Commented Jun 22 at 9:12

use ReflectionTestUtils.setField method

Samadhan Ghagare's user avatar

  • As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center . –  Community Bot Commented 2 days ago

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 .

Not the answer you're looking for? Browse other questions tagged java spring-boot testing junit mockito or ask your own question .

  • Featured on Meta
  • Upcoming sign-up experiments related to tags
  • The return of Staging Ground to Stack Overflow
  • Should we burninate the [lib] tag?
  • Policy: Generative AI (e.g., ChatGPT) is banned
  • What makes a homepage useful for logged-in users

Hot Network Questions

  • bmatrix* from mathtools results in huge column spacing when using [S]
  • If the slope of a secant is always irrational, is the function linear?
  • A chess engine in Java: generating white pawn moves
  • How Does the Blockchain Recognize Locked UTXOs in a PSBT if the PSBT Isn't Stored On-Chain?
  • Why does configure script expect an absolute directory name for --prefix?
  • Idiom for a situation where a problem has two simultaneous but unrelated causes?
  • Trying to determine what this item is
  • Have there been any scholarly attempts and/or consensus as regards the missing lines of "The Ruin"?
  • Familiar senses outside of a turn order
  • Can a planet have a warm, tropical climate both at the poles and at the equator?
  • Did James Madison say or write that the 10 Commandments are critical to the US nation?
  • Are both vocal cord and vocal chord correct?
  • Drawing waves using tikz in latex
  • Tubeless tape width?
  • How to Control StringContainsQ
  • QGIS Labeling expression to format a values list in a series of 2 columns of 2 records
  • Co-authors with little contribution
  • Folk stories and notions in mathematics that are likely false, inaccurate, apocryphal, or poorly founded?
  • Should I accept an offer of being a teacher assistant without pay?
  • How to patch command to work differently in math mode?
  • Why can Ethernet NICs bridge to VirtualBox and most Wi-Fi NICs don't?
  • What is the meaning of the angle bracket syntax in `apt depends`?
  • Collaborators write their departments for my (undergraduate) affiliation
  • Synthesis of racemic nicotine

how to write the junit for void method

IMAGES

  1. Write two Junit tests for one method: Write a

    how to write the junit for void method

  2. #14 Mockito Tutorial

    how to write the junit for void method

  3. JUnit Tools for Spring

    how to write the junit for void method

  4. How to write Junit test cases for constructor in java

    how to write the junit for void method

  5. Mastering Void Method Testing with Mockito & JUnit 5 in Spring Boot

    how to write the junit for void method

  6. Solved please write the method correctly and do the JUnit

    how to write the junit for void method

VIDEO

  1. 2.4

  2. JUnit

  3. How to use Assert Iterable Equals in JUNIT-5 || Spring Boot || #junit #springboot #assertion

  4. [Java Testing 4] jUnit : Test value typed double and void method

  5. Java :Mockito

  6. JUnit Tutorial 05 :- Performance Testing using JUnit

COMMENTS

  1. JUnit Test Void Method Example

    Click File -> New -> Maven Project .See below screen for modifications and click on Next button. Figure 1: JUnit Test Void Method Example Setup 1. On next screen fill in all the details as shown below and click on the Finish button. Figure 2: JUnit Test Void Method Example Setup 2. With this, we are ready with the blank Maven project.

  2. Mocking Void Methods with Mockito

    In this brief article, we covered four different ways to approach void methods when testing with Mockito. As always, the examples are available in this GitHub project . Partner - Bellsoft - NPI EA (cat = Spring)

  3. How do I test a very simple void method in jUnit?

    In my actual task, there is a requirement which says, the jUnit test must cover >60%. So I need to test a very simple method to reach this 60%. The method is the following: public void updateGreen() {. // delete this outprint if the Power Manager works. System.out.println(onCommand + "-green"); // p = Runtime.getRuntime().exec(command + "-green ...

  4. Unit testing void methods with Mockito and JUnit

    Mockito provides us with a verify () method which lets us verify whether the mock void method is being called or not. It lets us check the number of methods invocations. So if the method invocation returns to be zero we would know that our mock method is not being called. The verify method takes two arguments.

  5. Writing Tests with JUnit 5

    Now the JUnit dependency is set up correctly, we can create our first JUnit 5 test. Create an ExampleTest using the shortcut to generate code ( ⌘N or Alt+Insert) in the project window. Use the same shortcut again inside the class itself to get IntelliJ IDEA to generate a new valid test method for us.

  6. Java Unit Test void methods

    Void methods can be used with Mockito's doNothing (), doThrow (), and doAnswer () methods. doNothing () doThrow (): test when our method throw some exception. doAnswer (): Use this to do some operations when void method is called. System.out.println("Employee setName Argument = " + i.getArgument(0)); assertTrue("Pankaj".equals(i.getArgument(0)));

  7. JUnit 5 User Guide

    The JUnit Platform serves as a foundation for launching testing frameworks on the JVM. It also defines the TestEngine API for developing a testing framework that runs on the platform. Furthermore, the platform provides a Console Launcher to launch the platform from the command line and the JUnit Platform Suite Engine for running a custom test suite using one or more test engines on the platform.

  8. Java Junit 5 Mockito doNothing() Example

    Mockito's doNothing() is used when you want to test void methods because void methods do not return anything so there is no way you can verify using assert. These void methods may be anywhere, for example, in service class, in dao class, etc. Prerequisites. Eclipse 2020-06, Java at least 1.8, Junit 5, Gradle 6.5.1

  9. JUnit 5 tutorial

    JUnit 5 comes with multiple assert statements, which allows you to test your code under test. Simple assert statements like the following allow to check for true, false or equality. All of them are static methods from the org.junit.jupiter.api.Assertions.* package.

  10. JUnit Tests: How To Write JUnit Test Case With Examples

    Create JUnit Tests In Eclipse. Let's begin creating the JUnit test in Eclipse. #1) Open Eclipse. #2) Create a Project folder through the navigation flow: File->New->Java Project. Another window opens up where the user needs to enter the Project folder name. The screenshot is given below.

  11. Unit testing a void method

    Code. getShoppingCart(); However, I'm not sure what the best way to write a unit test for postLogin is. Approach 1. Use verify from Mockito to simply verify that the method was called. Approach 2. Test the side effect of the method call by fetching the value of the user's shopping cart.

  12. In Java, How to test void method in Junit Mockito with assertion?

    1. I would assume that your void method that needs to be tested is update in MyServiceImpl. Firstly, you can verify if dyDBDAO.save() is called. Mockito.verify(dyDBDAO).save(Mockito.anyList...); Secondly, you can check the modified or created records in the database by retrieving them and comparing to the inputs from getMockDetails.

  13. JUnit Tutorial

    The org.junit.Assert class provides methods to assert the program logic. Methods of Assert class. The common methods of Assert class are as follows: void assertEquals(boolean expected,boolean actual): checks that two primitives/objects are equal. It is overloaded. ... Write the test case. Here, we are using JUnit 4, so there is no need to ...

  14. Test Main Method with JUnit

    The main () method serves as the starting point for each Java application, and it might look different depending on the app type. In the case of regular web applications, the main () method will be responsible for context start, but in the case of some console applications, we'll put business logic to it. Testing the main () method is quite ...

  15. Guide to JUnit 5 Parameterized Tests

    JUnit 5 test runner executes this above test — and consequently, the isOdd method — six times. And each time, it assigns a different value from the @ValueSource array to the number method parameter. So, this example shows us two things we need for a parameterized test: a source of arguments, in this case, an int array.

  16. How to write JUnit for Void method

    Like that you have to do. ocjp 6 — Feeding a person with food is a great thing in this world. Feeding the same person by transferring the knowledge is far more better thing. The reason is the amount of satisfaction which we get through food is of only one minute or two. But the satisfaction which we can get through the knowledge is of life long.

  17. java

    You save result into private member. For that you need to get that member using the getter method or WhiteBox class of PowerMock package. for getter method add into that class. public String getRoman() { return this.roman; } using WhiteBox add following statement into test case after method call.

  18. How to verify that void methods were called using Mockito

    Mockito framework could help us mock and verify that method call. Here is how we can do it: SomeClassTest.java. The most important things to highlight in this test class are: The class under test ...

  19. PDF JUnit 5 User Guide

    6. Advanced Topics. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151

  20. Lab: Skills

    JUnit has an Assert class that has a static assertEquals() method with the following signature that is used to compare expected and actual results: public static void assertEquals(int expected, int actual, String description) . where description is a human-readable String describing the test, expected is the expected result, and actual is the result of actually running the code being tested.

  21. How to test a void method using JUnit and/or Mockito

    Put the input files into a directory, and the expected ones into another one, but set the same names for each pair of files ( case1.xml and case1.csv ). Code a JUnit class with a private method which should do the test and the comparison, and then add one @Test method for each case you want to test:

  22. A Guide to Interfaces and Abstract Classes in Java

    They can define common properties and methods that all subclasses inherit. This promotes code reuse and reduces redundancy, as you don't need to write the same code in every subclass. Abstract Methods: Abstract classes have the power to define abstract methods. These methods lack an implementation within the abstract class itself.

  23. java

    You can either use doNothing or doThrow on your mock to mock the behaviour of your mock. or. However, doNothing is not actually needed as this would be the default behaviour for a mock function with a void return type. You may want however to verify that this method was called.

  24. How to use class member variables inside Junit-Mockito tests

    a) redesign your class to be testable b) move method out of class and make public static, so it can be tested independent of class for any kind of list c) use reflection to assign the field d) call your complex methods and have your list initialized.And honestly, I wouldn't test that method separately, it looks like a private implementation detail and should be covered by other tests that ...