EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login

JUnit assert exception

Secondary Sidebar
JUnit Tutorial
  • Junit
    • JUnit 5 Assert
    • JUnit RunWith
    • JUnit AssertThat
    • JUnit Report
    • JUnit BeforeClass
    • JUnit Framework
    • JUnit Data Provider
    • JUnit Runner
    • JUnit 5 Parameterized Tests
    • JUnit BeforeAll
    • JUnit Private Methods
    • JUnit Integration Test
    • JUnit Maven Dependency
    • JUnit Annotations?
    • JUnit Testing
    • JUnit Test Order
    • JUnit 5 RunWith
    • JUnit 4 Maven
    • JUnit Jar
    • JUnit assertEquals
    • JUnit 5 Parameterized Test
    • JUnit Dependency
    • JUnit Fail
    • JUnit Disable Test
    • JUnit Assert
    • JUnit in Maven
    • JUnit 5 Gradle
    • JUnit XML
    • JUnit XML Format
    • JUnit Eclipse
    • JUnit Test Suite
    • JUnit Parameterized Test
    • JUnit assert exception
    • JUnit Code Coverage
    • JUnit Jupiter
    • JUnit Rule
    • JUnit version
    • Junit Interview Questions
Home Software Development Software Development Tutorials JUnit Tutorial JUnit assert exception

JUnit assert exception

Definition of JUnit assert exception

JUnit is an open-source tool and it provides the different types of exceptions to the developer, in which that assertion is one of the exceptions that are available in JUnit. Basically assert is used to validate the functionality. Normally this takes the sort of the normal special case and an Executable practical connection point where we can finish the code under assessment through a lambda articulation. In another word, we can say that an assert exception is used to throw the exception when the condition does not match, assert the exception we can implement as per our requirements.

What is JUnit assert exception?

JUnit gives a choice of following the exemption treatment of code. You can test whether or not the code tosses an ideal exemption. The normal boundary is utilized alongside the @Test comment. Allow us to see @Test (expected) in real life.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Moreover, it’s essential to take note that this affirmation is fulfilled when the encased code tosses a special case of type NumberFormatException or any of its determined sorts.

All in One Software Development Bundle(600+ Courses, 50+ projects)
Python TutorialC SharpJavaJavaScript
C Plus PlusSoftware TestingSQLKali Linux
Price
View Courses
600+ Online Courses | 50+ projects | 3000+ Hours | Verifiable Certificates | Lifetime Access
4.6 (86,064 ratings)

This means that assuming we pass Exception as the normal special case type, any exemption tossed will cause the declaration to prevail since Exception is the super-type for all special cases.

To compose and run the experiments for a special case, we want the JUnit container record in the framework, or we really want to set up the JUnit climate in our framework. To test the special cases, we ought to follow the accompanying advances:

  • Make a class to be tried
  • Make an experiment class for testing special cases
  • Make a Test Runner class to execute the experiment

JUnit assert exception test

The unit gives the office to follow the special case and furthermore to check whether or not the code is tossing anticipated exemption.
JUnit4 gives a simple and coherent way for exemption testing, you can utilize

Discretionary boundary (expected) of @test comment and While Testing special case, you really want to guarantee that the exemption class you are giving in that discretionary boundary of @test explanation is something similar. This is on the grounds that you are expecting an exemption from the strategy you are Unit Testing, in any case, our JUnit test would come up short.

Example@Test(expected=exception.class)

By utilizing the “anticipated” boundary, you can determine the special case name our test might toss. In the above model, you are utilizing an “exception” which will be tossed by the test on the off chance that a designer utilizes a contention that isn’t allowed.
Now let’s see examples for better understanding as follows.

First, we need to create a class sampletest and write the following code as follows.

package com.demo;
public class sampletest {
private String msg;
//Constructor
//@param message to be printed
public sampletest(String msg){
this.msg = msg;
}
// prints the message
public void printmsg(){
System.out.println("Specified msg");
int x = 0;
int y = 1/x;
}
// add to the message
public String addmsg(){
msg = "string " + msg;
System.out.println(msg);
return msg;
}
}

Explanation

In the above program, we try to implement a divide by zero exception.
Now we need to create a test class and write the following code as follows.

import org.JUnit.Test;
import org.JUnit.Ignore;
import static org.JUnit.Assert.assertEquals;
public class demotest {
String msg = "Harry";
sampletest sampletest = new sampletest(msg);
@Test(expected = ArithmeticException.class)
public void PrintMessage() {
System.out.println("printMessage");
sampletest.PrintMessage();
}
@Test
public void testMessage() {
System.out.println("addmsg");
msg = "Result of" + "Harry";
System.out.println("msg ");
assertEquals(msg,sampletest.printmsg());
}
}

Now we need to create the runner class to execute the program as below.

import org.JUnit.runner.JUnitCore;
import org.JUnit.runner.Result;
import org.JUnit.runner.notification.Failure;
public class TestRunner {
public static void main(String[] args) {
r r = JUnitCore.runClasses(demotest.class);
for (Failure failure : r.getFailures()) {
System.out.println(failure.toString());
}
System.out.println(r.wasSuccessful());
}
}

Explanation

In the above code, we implement the test runner to see the result. The final result of the above implementation we illustrated by using the following screenshot as follows.

28

JUnit assert exception Message

Now let’s see a message in assert as follows.
While testing code you regularly need to test that a specific exemption and message are tossed. The JUnit technique to do this is Assertions.assertThrows. So to test a NullPointerException is tossed we would utilize this:

Assertions.assertThrows(NullPointerException.class, ()- > {codeThatThrowsNPE;}) One thing not satisfactory from the docs is the way to test the exemption message.

Now let’s see an example for better understanding as follows.

exceptionThatWasThrown: Throwable =
assertThrows(NullPointerException::class.java) {
codeThatThrows
}
assertThat(exceptionThatWasThrown.message, equalTo("Msg Exception thrown"))

JUnit assert exception Examples

Now let’s see the different examples for better understanding as follows.

package com.demo;
public class Cal{
public static int max(int array[]){
int m=0;
for(int i=1;i<array.length;i++){
if(m<array[i])
m=array[i];
}
return m;
}
}

Explanation

Here we create Cal class and write the above code, here we try to find out the max number array. The logic of finding the max number is shown in the above code.

Here, we are utilizing JUnit 4, so there is no compelling reason to acquire TestCase class. The principle testing code is written in the maxnumber() method. In any case, we can likewise play out some undertakings when each test, the code as shown below.

package com.demo;
import static org.JUnit.Assert.*;
import com.javatpoint.logic.*;
import org.JUnit.Test;
public class TestCase{
@Test
public void testFindMax(){
assertEquals(5,Cal.max(new int[]{2,4,5,1}));
assertEquals(-2,Cal.max(new int[]{-13,-2,-4,-6,-8}));
}
}

Explanation

In the above code, we can see we try to pass negative value and max function returns the 0, so it is incorrect logic. The final result of the above implementation we illustrated by using the following screenshot as follows.

29

Now write the correct logic above the program as below.

package com.demo;
public class Cal{
public static int max(int array[]){
int m=array[0];
for(int i=1;i<array.length;i++){
if(m<array[i])
m=array[i];
}
return m;
}
}

Explanation

In the above program, we just made the changes in the declaration, instead of m = 0 we write m = array [0] as shown in the above code. Save the program and run.

Conclusion

We hope from this article you learn more about the JUnit assert exception. From the above article, we have taken in the essential idea of the JUnit assert exception and we also see the representation and example of the JUnit assert exception. From this article, we learned how and when we use the JUnit assert exception.

Recommended Articles

This is a guide to JUnit assert exception. Here we discuss the Definition, What is JUnit assert exception, messages, examples with code implementation. You may also look at the following articles to learn more-

  1. JUnit Parameterized Test
  2. JUnit Jupiter
  3. JUnit 5 Maven Dependency
  4. JUnit Test Suite
0 Shares
Share
Tweet
Share
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2022 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Software Development Course

C# Programming, Conditional Constructs, Loops, Arrays, OOPS Concept

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more

Special Offer - All in One Software Development Bundle (600+ Courses, 50+ projects) Learn More