Showing posts with label junit. Show all posts
Showing posts with label junit. Show all posts

Tuesday, February 15, 2022

EXAMPLES: JUnit in Eclipse IDE

Below are examples of JUnit Jupiter @ annotations.

Example 1 (@Test) :-

>> in file path: JUnittest-demo
src/main/java

//MyClass.java
package com.unittest;

public class myClass {

    public int sum(int a, int b) {
        return a+b;
    }
}

>> in file path: JUnittest-demo
src/test/java

//myTestForClass.java
package com.unittest;

//imports
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;

public class myunittest {

    @Test
    void test() {
        MyClass objmyclass= new MyClass();
        int actualresult;
        int expected ;
        for(int i=1;i<=10;i++)
        {
            actualresult= objmyclass.sum(i, i+1);
            if(i%2==0)
                expected= i+i+1;
            else
                expected=10;
            assertEquals(expected, actualresult);
        } 
        //fail("Not yet implemented");
    }
}

Example 2 (@Test with all Passed)

package com.unittest; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; public class myTestForClass {
@Test void test_sum() { myClass objmyclass = new myClass(); int actualresult; int expected ; for(int i=1; i<=10; i++) { actualresult = objmyclass.sum(i, i+1); expected = i+i+1; assertEquals(expected, actualresult); } }
@Test
void test_subt() { myClass objmyclass = new myClass(); int actualresult; int expected ; for(int i=1; i<=10; i++) { actualresult = objmyclass.subt(i, i+1); expected = i-(i+1); assertEquals(expected, actualresult); } }
@Test void test_divide() { myClass objmyclass = new myClass(); int actualresult; int expected ; for(int i=1; i<=10; i++) { actualresult = objmyclass.divide(i, i+1); expected = i/(i+1); assertEquals(expected, actualresult); } } }

Example 3 (@BeforeAll):-

// setting up value of variable i at class level which can used by other test methods

import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;

public class myunittest {
   static int i;
    
@Test
    void test() {
        System.out.println("test method is called " + i);
        MyClass objmyclass= new MyClass();
        int actualresult;
        int expected ;
        for(int i=1;i<=10;i++)
        {
            actualresult= objmyclass.sum(i, i+1);         
            expected= i+i+1;
            assertEquals(expected, actualresult);
        }
        
        //fail("Not yet implemented");
    }

@Test
    void newTest() {
        System.out.println("failed method is called" + i);
        String mystr="Testing";
        if(mystr.contains("t")) 
        {
            fail("This test case is failed");
        }
    }
    
@BeforeAll
    static void setup() {
        i=5;
         System.out.println("this is my test class ");
     }    
}

Example 4 (@BeforeEach):-

package com.unittest; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; public class myTestForClass { static int i; @Test void a() { i=30; System.out.println("'a' test method is called " + i); myClass objmyclass = new myClass(); int actualresult; int expected; for(int i=1;i<=10;i++) { actualresult= objmyclass.sum(i, i+1); expected= i+i+1; assertEquals(expected, actualresult); } } @Test void b() { System.out.println("'b' failed method is called" + i); String mystr="Testing"; if(mystr.contains("t")) { fail("This test case is failed"); } } @Test void c() { System.out.println("'c' This is mytest example"); } //@BeforeAll is an annotation which get executed in the first instance. @ BeforeAll static void setup() { i=5; System.out.println("this is will appear Before ALL test classes "); } //@BeforeEach is an annotation which get executed on each TestCase(@Test) @ BeforeEach void setupEachTest() { System.out.println("this will appear Before EACH method is called"); i=20; } }



Example 5 (@DisplayName and @Disabled):-

@DisplayName ("Step 1") @Test void a() { i=30; System.out.println("'a' test method is called " + i); myClass objmyclass = new myClass(); int actualresult; int expected; for(int i=1;i<=10;i++) { actualresult= objmyclass.sum(i, i+1); expected= i+i+1; assertEquals(expected, actualresult); } } @Disabled ("This is disabled because keep on failing") @Test void b() { System.out.println("'b' failed method is called" + i); String mystr="Testing"; if(mystr.contains("t")) { fail("This test case is failed"); } } @DisplayName ("Step 3") @Test void c() { System.out.println("'c' This is mytest example"); }


Example 6 (groupAssertions):-

(will fail)
@Test
	 void groupAssertions() {
	     int[] numbers = {0, 1, 2, 3, 4};
	     assertAll("numbers",
	         () -> assertEquals(numbers[0], 1),
	         () -> assertEquals(numbers[3], 3),
	         () -> assertEquals(numbers[4], 1)
	     );
	 }
(will pass)
@Test
	 void groupAssertions() {
	     int[] numbers = {0, 1, 2, 3, 4};
	     assertAll("numbers",
	         () -> assertEquals(numbers[0], 0),
	         () -> assertEquals(numbers[3], 3),
	         () -> assertEquals(numbers[4], 4)
	     );
	 }
Example 7 (assertThrows):-
@Test 
        void shouldThrowException() { 
            Throwable exception = assertThrows(UnsupportedOperationException.class, () -> { 
                    throw new UnsupportedOperationException("Not supported"); 
            }); 
            assertEquals(exception.getMessage(), "Not supported"); 
        

@Test 
        void assertThrowsException() { 
            String str = null; assertThrows(IllegalArgumentException.class, () -> { 
                    Integer.valueOf(str); }); 
        }

Monday, February 14, 2022

JUnit


JUnit 5

 Unit testing involves the testing of each unit or an individual component of the software application. It is the first level of functional testing. The aim behind unit testing is to validate unit components with their performance.

JUnit5 main aim is to adapt the Java 8 style of coding. Minimum Jdk8 is required to execute JUnit 5 tests.

Architecture

JUnit 5 contains a different set of modules from its subprojects. 

  1. JUnit Platform
  2. JUnit Jupiter
  3. JUnit Vintage


1. JUnit Platform

The platform is responsible for launching testing frameworks on the JVM (Java Virtual Machine). It defines a stable and powerful interface between JUnit and its clients, such as build tools.

The platform easily integrates clients with JUnit to discover and execute tests.

It also defines the TestEngine API (Application Program Interface)  for developing a testing framework that runs on the JUnit platform. By implementing a custom TestEngine, we can plug 3rd party testing libraries directly into JUnit.


2. JUnit Jupiter

This module includes new programming and extension models for writing tests in JUnit 5. New annotations (whatever starts with '@') in comparison to JUnit 4 are:

@TestFactory – denotes a method that's a test factory for dynamic tests

@DisplayName – defines a custom display name for a test class or a test method

@Nested – denotes that the annotated class is a nested, non-static test class

@Tag – declares tags for filtering tests

@ExtendWith – registers custom extensions

@BeforeEach – denotes that the annotated method will be executed before each test method (previously @Before)

@AfterEach – denotes that the annotated method will be executed after each test method (previously @After)

@BeforeAll – denotes that the annotated method will be executed before all test methods in the current class (previously @BeforeClass)

@AfterAll – denotes that the annotated method will be executed after all test methods in the current class (previously @AfterClass)

@Disable – disables a test class or method (previously @Ignore)


3. JUnit Vintage

JUnit Vintage supports running tests based on JUnit 3 and JUnit 4 on the JUnit 5 platform. Basically testing in a backward compatibility.




4. Basic Annotation:-

Example 1

        @Test
	void testSingleSuccessTest() {
	System.out.println("Success Test");
	}
	@BeforeAll
	static void setup() {
	   System.out.println("@BeforeAll - executes once before all test methods in this class");
	}

	@BeforeEach
	void init() {
		System.out.println("@BeforeEach - executes before each test method in this class");
	}	

Example 2

        @DisplayName("Single test successful")
	@Test
	void testSingleSuccessTest() {
	System.out.println("Success Test");
	}
	@Disabled("Not implemented yet")
	@Test
	void avoidTesting() {
		
	}

Example 3

        @Test
	void SingleAssertion()
	{
		assertEquals(2,3);
	}
	@Test
	 void groupAssertions() {
	     int[] numbers = {0, 1, 2, 3, 4};
	     assertAll("numbers",
	         () -> assertEquals(numbers[0], 1),
	         () -> assertEquals(numbers[3], 3),
	         () -> assertEquals(numbers[4], 1)
	     );
	 }

Example 4

        @Test
	void shouldThrowException() {
	    Throwable exception = assertThrows(UnsupportedOperationException.class, () -> {
	      throw new UnsupportedOperationException("Not supported");
	    });
	    assertEquals(exception.getMessage(), "Not supported");
	}

	@Test
	void assertThrowsException() {
	    String str = null;
	    assertThrows(IllegalArgumentException.class, () -> {
	      Integer.valueOf(str);
	    });
	}

Fluentd

Open-source log data collector > why logs? - for compliance (auditing, company, business) - for security (transparency, monitoring, admin...