Updated March 30, 2023
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.
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.
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.
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.
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-