...

Software Testing - Junit

Back to Course

Lesson Description


Lession - #1212 Junit Assertions


Assertions are utility techniques to help asserting conditions in tests; these methods are accessible through the Assert class, in JUnit 4, and the Assertions one, in JUnit 5.

What is assertion in unit testing?

A statement is a boolean expression at a particular point in a program which will be true except if there is a bug in the program. A test assertion is characterized as an expression, which encapsulates some logic indicated specified an objective under test.

What is the reason for JUnit assertion statements?

assertSame. Asserts that two objects refer to a similar object. In the event that they are not same, an AssertionError without a message is thrown.

Methods of assertions



Let's see an example



import static org.junit.Assert.*;				
import org.junit.Test;		


public class Junit4AssertionTest {				

    @Test		
    public void testAssert(>
{ //Variable declaration String string1="Junit"; String string2="Junit"; String string3="test"; String string4="test"; String string5=null; int variable1=1; int variable2=2; int[] airethematicArrary1 = { 1, 2, 3 }; int[] airethematicArrary2 = { 1, 2, 3 }; //Assert statements assertEquals(string1,string2>
; assertSame(string3, string4>
; assertNotSame(string1, string3>
; assertNotNull(string1>
; assertNull(string5>
; assertTrue(variable1<variable2>
; assertArrayEquals(airethematicArrary1, airethematicArrary2>
; } }
TestRunner.java

package guru99.junit;		

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>
{ Result result = JUnitCore.runClasses(Junit4AssertionTest.class>
; for (Failure failure : result.getFailures(>
>
{ System.out.println(failure.toString(>
>
; } System.out.println("Result=="+result.wasSuccessful(>
>
; } }