Junit in java

JUnit is a simple framework for testing of java language. It is an instance of the xUnit architecture for unit testing frameworks.

Junit Classes

Assert :

A set of assertion methods useful for writing tests. Only failed assertions are recorded.

These methods can be used directly:

Assert.assertEquals(...), however, they read better if they are referenced through static import:

 import static org.junit.Assert.*;
    ...
    assertEquals(...);

Assume :

A set of methods useful for stating assumptions about the conditions in which a test is meaningful. A failed assumption does not mean the code is broken, but that the test provides no useful information. Assume basically means "don't run this test if these conditions don't apply". The default JUnit runner skips tests with failing assumptions. Custom runners may behave differently.

A good example of using assumptions is in Theories where they are needed to exclude certain datapoints that aren't suitable or allowed for a certain test case.

Failed assumptions are usually not logged, because there may be many tests that don't apply to certain configurations. These methods can be used directly: Assume.assumeTrue(...), however, they read better if they are referenced through static import:

 import static org.junit.Assume.*;
    ...
    assumeTrue(...);
	

Test.None :

Default empty exception

Junit Annotation

After :

If you allocate external resources in a Before method you need to release them after the test runs. Annotating a public void method with @After causes that method to be run after the Test method. All @After methods are guaranteed to run even if a Before or Test method throws an exception. The @After methods declared in superclasses will be run after those of the current class, unless they are overridden in the current class.

Here is a simple example:

 package JUnit;  import static org.junit.Assert.*;  import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test;  public class additionTest {  	JunitMainClass junitMainClass; 	 	@After 	public void afterTest(){ 		junitMainClass = new JunitMainClass(); 		System.out.println("After test"); 	} 	 	@Test 	public void test() { 		System.out.println("test in mid"); 		 		int result = junitMainClass.addition(10, 10); 		assertEquals(20, result); 	} 	 } 

AfterClass

If you allocate expensive external resources in a BeforeClass method you need to release them after all the tests in the class have run. Annotating a public static void method with @AfterClass causes that method to be run after all the tests in the class have been run. All @AfterClass methods are guaranteed to run even if a BeforeClass method throws an exception. The @AfterClass methods declared in superclasses will be run after those of the current class, unless they are shadowed in the current class.

Here is a simple example:

 package JUnit;  import static org.junit.Assert.*;  import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test;  public class additionTest {  	JunitMainClass junitMainClass; 	 	@org.junit.AfterClass 	public static void AfterClass(){ 		System.out.println("After class test"); 	} 	 	@Test 	public void test() { 		System.out.println("test in mid"); 		 		int result = junitMainClass.addition(10, 10); 		assertEquals(20, result); 	} 	 } 

Before

When writing tests, it is common to find that several tests need similar objects created before they can run. Annotating a public void method with @Before causes that method to be run before the Test method. The @Before methods of superclasses will be run before those of the current class, unless they are overridden in the current class. No other ordering is defined.

Here is a simple example:

 package JUnit;  import static org.junit.Assert.*;  import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test;  public class additionTest {  	JunitMainClass junitMainClass; 	 	@Before 	public void beforeTest(){ 		junitMainClass = new JunitMainClass(); 		System.out.println("before test"); 	} 	 	@Test 	public void test() { 		System.out.println("test in mid"); 		 		int result = junitMainClass.addition(10, 10); 		assertEquals(20, result); 	} 	 }

BeforeClass :

Sometimes several tests need to share computationally expensive setup (like logging into a database). While this can compromise the independence of tests, sometimes it is a necessary optimization. Annotating a public static void no-arg method with @BeforeClass causes it to be run once before any of the test methods in the class. The @BeforeClass methods of superclasses will be run before those of the current class, unless they are shadowed in the current class.

For example:

 package JUnit;  import static org.junit.Assert.*;  import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test;  public class additionTest {  	JunitMainClass junitMainClass; 	@BeforeClass 	public static void BeforeClass(){ 	System.out.println("BeforeClass before all test cases");	 	} 	 	@Test 	public void test() { 		System.out.println("test in mid"); 		 		int result = junitMainClass.addition(10, 10); 		assertEquals(20, result); 	} 	 } 

ClassRule :

Annotates static fields that reference rules or methods that return them. A field must be public, static, and a subtype of TestRule. A method must be public static, and return a subtype of TestRule.

The Statement passed to the TestRule will run any BeforeClass methods, then the entire body of the test class (all contained methods, if it is a standard JUnit test class, or all contained classes, if it is a Suite), and finally any AfterClass methods.

The statement passed to the TestRule will never throw an exception, and throwing an exception from the TestRule will result in undefined behavior. This means that some TestRules, such as ErrorCollector, ExpectedException, and Timeout, have undefined behavior when used as ClassRules.

If there are multiple annotated ClassRules on a class, they will be applied in an order that depends on your JVMs implementation of the reflection API, which is undefined, in general. However, Rules defined by fields will always be applied before Rules defined by methods.

For example, here is a test suite that connects to a server once before all the test classes run, and disconnects after they are finished:

 package JUnit;  import org.junit.ClassRule; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses;  @RunWith(Suite.class) @SuiteClasses({ additionTest.class, testWordCount.class , testbolTest.class}) public class AllTests { 	 	public static JunitMainClass myServer= new JunitMainClass();     @ClassRule     public static JunitMainClass resource= new JunitMainClass() {            protected void before() throws Throwable {          myServer.addition(12, 12);      }           protected void after() {          myServer.CountWord("Elephant");      }   };  }  

FixMethodOrder :

This class allows the user to choose the order of execution of the methods within a test class.

The default order of execution of JUnit tests within a class is deterministic but not predictable. The order of execution is not guaranteed for Java 7 (and some previous versions), and can even change from run to run, so the order of execution was changed to be deterministic (in JUnit 4.11)

It is recommended that test methods be written so that they are independent of the order that they are executed. However, there may be a number of dependent tests either through error or by design. This class allows the user to specify the order of execution of test methods.

For possibilities, see MethodSorters Here is an example:

  @FixMethodOrder(MethodSorters.NAME_ASCENDING)  public class MyTest {  }  

Ignore :

Sometimes you want to temporarily disable a test or a group of tests. Methods annotated with Test that are also annotated with @Ignore will not be executed as tests. Also, you can annotate a class containing test methods with @Ignore and none of the containing tests will be executed. Native JUnit 4 test runners should report the number of ignored tests along with the number of tests that ran and the number of tests that failed.

For example:

     @Ignore @Test public void something() { ...   @Ignore takes an optional default parameter if you want to record why a test is being ignored:     @Ignore("not ready yet") @Test public void something() { ...   @Ignore can also be applied to the test class:       @Ignore public class IgnoreMe {           @Test public void test1() { ... }           @Test public void test2() { ... }          }  
Rule :

Annotates fields that reference rules or methods that return a rule. A field must be public, not static, and a subtype of TestRule (preferred) or MethodRule. A method must be public, not static, and must return a subtype of TestRule (preferred) or MethodRule.

The Statement passed to the TestRule will run any Before methods, then the Test method, and finally any After methods, throwing an exception if any of these fail. If there are multiple annotated Rules on a class, they will be applied in order of fields first, then methods. However, if there are multiple fields (or methods) they will be applied in an order that depends on your JVM implementation of the reflection API, which is undefined, in general. Rules defined by fields will always be applied before Rules defined by methods. You can use a RuleChain if you want to have control over the order in which the Rules are applied.

For example, here is a test class that creates a temporary folder before each test method, and deletes it after each:

How to write Junit test in java

1. Create a java class like.. JunitMainClass.java

package JUnit;

public class JunitMainClass {

	public int addition(int x, int y){
		return x  + y;
	}
	
	public String CountWord(String word){
		return word;
	}
	
	public boolean bolTest(int n, int m){
		boolean condition=false;
		int result = n/m;
		if(result==2){
			condition = true;
		}
		return condition;
		 
	}
	
}

2. Add junit.jar version any like 4.12 v

Create addition Test case beacause , In JunitMainClass has method to test

JunitTestCase

Then write the program additionTest.java

package JUnit;

import static org.junit.Assert.*;

import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

public class additionTest {

	JunitMainClass junitMainClass;
	@BeforeClass
	public static void BeforeClass(){
	System.out.println("BeforeClass before all test cases");	
	}
	
	@org.junit.AfterClass
	public static void AfterClass(){
		System.out.println("After class test");
	}
	
	
	@Before
	public void beforeTest(){
		junitMainClass = new JunitMainClass();
		System.out.println("before test");
	}
	
	@After
	public void afterTest(){
		junitMainClass = new JunitMainClass();
		System.out.println("After test");
	}
	
	@Test
	public void test() {
		System.out.println("test in mid");
		
		int result = junitMainClass.addition(10, 10);
		assertEquals(20, result);
	}
	
}

3. we have also made a method CountWord in JunitMainClass class, so also will write test case for that like testWordCount.java

package JUnit;

import static org.junit.Assert.*;

import org.junit.Test;

public class testWordCount {

	@Test
	public void test() {
		JunitMainClass class1 = new JunitMainClass();
		String result = class1.CountWord("elephant");
		int countWord =0;
		for(int i = 0;  i
			if(result.charAt(i) =='e' || result.charAt(i) =='E' ){
				countWord ++;
			}
		}
	assertEquals(2, countWord);
	}

}

4. Again we have also made a method bolTest(int n, int m) in JunitMainClass class, so also will write test case for that like testBolTest.java

package JUnit;

import static org.junit.Assert.*;

import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

public class testbolTest {

	
	@Test
	public void test() {
		
		JunitMainClass class1 = new JunitMainClass();
		boolean result = class1.bolTest(6, 3);
		assertEquals(true, result);
		
	}

}

5. Now ,click on junit test for run the all test classes each time using junit like, additionTest.java, testBolTest.java, testWordCount.java that junit testing is success or not

Run JUnit

6. If junit run successful then console message come and shown bellow image :

junitRunSuccess

7. After finish these thing, we create all test in single time usig Junit test suite

allSuitTest

listofmethod

8. create allTest.java

package JUnit;

import org.junit.ClassRule;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;

@RunWith(Suite.class)
@SuiteClasses({ additionTest.class, testWordCount.class , testbolTest.class})
public class AllTests {
	

}

9. then create alltest.java that is JUnit test suite file< and /p>

alltestcaseSuccessful

Link
Eng. Ravi Kumar Verma

Simple and dept learning technology is very important part in software development. Same story has been implemented at this site, so learn and implement the inovative things, Thanks

Ravi Kumar Verma