Category Archives: JUNIT Testing framework

* Selenium Automation Learning Path *

Selenium learning Path

Selenium learning Path

How to parameterize test in junit with example

@Parameters

The custom runner Parameterized implements parameterized tests. When running a parameterized test class, instances are created for the cross-product of the test methods and the test data elements.

 how to convert array to list in java ?

package myWorkjUnit;

import java.util.Arrays;
import java.util.List;

public class ArrayToList {
 public static void main(String[] argv) {

 String sArray[] = new String []{"Array A", "Array B", "Array C"};

 //convert array to list
 List<String> lList = Arrays.asList(sArray);

 System.out.println(lList);

 }

}

package myWorkjUnit;

import java.util.Arrays;
import java.util.Collection;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;

/*Structure of a parameterized test class

1. A static method that generates and returns test data,
2. A single constructor that stores the test data, and
3. A test.
*/

@RunWith(value = Parameterized.class)
public class ParameterizedTestExample {
 private int number1;

 /*
 * Constructor.
 * The JUnit test runner will instantiate this class once for every
 * element in the Collection returned by the method annotated with
 * @Parameters.
 */

 public ParameterizedTestExample(int number) {
 this.number1 = number;
 }

 /*
 * Test data generator.
 * This method is called the the JUnit parameterized test runner and
 * returns a Collection of Arrays. For each Array in the Collection,
 * each array element corresponds to a parameter in the constructor.
 */
 @Parameters
 public static Collection<Object[]> data() {

// In this example, the parameter generator returns a List of
// arrays. Each array has two elements: { datum, expected }.
// These data are hard-coded into the class, but they could be
// generated or loaded in any way you like.
 Object[][] data = new Object[][] { { 1 }, { 2 }, { 3 }, { 4 } };

 //convert array to list
 return Arrays.asList(data);
 }

/*
 * The test.
 * This test method is run once for each element in the Collection returned
 * by the test data generator -- that is, every time this class is
 * instantiated. Each time this class is instantiated, it will have a
 * different data set, which is available to the test method through the
 * instance's fields.
 */
 @Test
 public void pushTest() {
 System.out.println( "Parameterized Number is : " + number1);
 }
}

</pre>
Parameterized Number is : 1
Parameterized Number is : 2
Parameterized Number is : 3
Parameterized Number is : 4
<pre>


 

 

References

References

 

 

 

 

 

 

References:

Parameterized (JUnit API)

Link 1 Link 2 Link 3 Link 4 Link 5

What @Rule in jUnit? What is ErrorCollector() in jUnit? How to use ErrorCollector()? Benefits of ErrorCollector()?

 

 

 

 

 

 


Annotation Type Rule
Annotates fields that contain rules. Such a field must be public, not static, and a subtype of TestRule. 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 an order that depends on your JVM’s implementation of the reflection API, which is undefined, in general. For example, here is a test class that creates a temporary folder before each test method, and deletes it after each:

Class ErrorCollector

The ErrorCollector rule allows execution of a test to continue after the first problem is found (for example, to collect _all_ the incorrect rows in a table, and report them all at once):

Example 1:

package myWorkjUnit;

import junit.framework.Assert;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ErrorCollector;

public class LearnAssertions {

/*
 * The ErrorCollector Rule allows execution of a test to continue after the
 * first problem is found and report them all at once
 */
 @Rule
 public ErrorCollector errCol = new ErrorCollector();

 @Test
 public void testAdvertisingPrograms(){
 System.out.println("open browser and go to URL");
 System.out.println("click on link");
 System.out.println("click on one Login link");

 String actual = "actual";
 String expected = "Expected";
// if("ElementLocation" == "ElementLocation from abve statement"){
// System.out.println("Pass");
// }else{
// System.out.println("fail");
// report Error
// }

 System.out.println("before Assert.assertEquals(expected, actual)");

 try {
 Assert.assertEquals(expected, actual);
 } catch (Throwable e) {
 System.out.println("Report Error" + e);
 errCol.addError(e);
 }

 System.out.println("After Assert.assertEquals(expected, actual)");

 }

}

&nbsp;

Example 2: Lets collect more errors ……………

package myWorkjUnit;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ErrorCollector;

public class UsesErrorCollectorTwice {
 /*
 * The ErrorCollector Rule allows execution of a test to continue after the
 * first problem is found and report them all at once
 */
 @Rule
 public ErrorCollector collector= new ErrorCollector();

@Test
 public void example() {
 collector.addError(new Throwable("first thing went wrong"));
 collector.addError(new Throwable("second thing went wrong"));

 // all lines will run, and then a combined failure logged at the end.
 }

}

ErrorCollector

ErrorCollector

References:

Rule (JUnit API)

ErrorCollector (JUnit API)

catch and handle assertion errors

Lets see what happens with lines after assertion statement

Assert.assertEquals(expected, actual);

 

package myWorkjUnit;

import junit.framework.Assert;

import org.junit.Test;

public class LearnAssertions {

@Test
 public void testAdvertisingPrograms(){
 System.out.println("open browser and go to URL");
 System.out.println("click on link");
 System.out.println("click on one Login link");

 String actual = "actual";
 String expected = "Expected";
// if("ElementLocation" == "ElementLocation from abve statement"){
// System.out.println("Pass");
// }else{
// System.out.println("fail");
// report Error
// }

 System.out.println("before Assert.assertEquals(expected, actual)");
 Assert.assertEquals(expected, actual);
 System.out.println("After Assert.assertEquals(expected, actual)");



 }

}

 

check out eclipse console after running above code using junit

 

following line of code is not executed because of assertion

System.out.println(“After Assert.assertEquals(expected, actual)”);

 

Lets handle this

We can use Try Catch block to handle assertion and catch error and continue further program execution.

package myWorkjUnit;

import junit.framework.Assert;

import org.junit.Test;

public class LearnAssertions {

@Test
 public void testAdvertisingPrograms(){
 System.out.println("open browser and go to URL");
 System.out.println("click on link");
 System.out.println("click on one Login link");

 String actual = "actual";
 String expected = "Expected";
// if("ElementLocation" == "ElementLocation from abve statement"){
// System.out.println("Pass");
// }else{
// System.out.println("fail");
// report Error
// }

 System.out.println("before Assert.assertEquals(expected, actual)");

 try {
 Assert.assertEquals(expected, actual);
 } catch (Throwable e) {
 System.out.println("Report Error" + e);
 }

 System.out.println("After Assert.assertEquals(expected, actual)");


 }

}

 

Lets check out console

 

Smart one 🙂

how to use assertions in junit ? part 1

What is assertion?

 

An assertion is a statement in the Java programming language that enables you to test your assumptions about your program. For example, if you write a method that calculates the speed of a particle, you might assert that the calculated speed is less than the speed of light.

Each assertion contains a boolean expression that you believe will be true when the assertion executes. If it is not true, the system will throw an error. By verifying that the boolean expression is indeed true, the assertion confirms your assumptions about the behavior of your program, increasing your confidence that the program is free of errors.

Experience has shown that writing assertions while programming is one of the quickest and most effective ways to detect and correct bugs. As an added benefit, assertions serve to document the inner workings of your program, enhancing maintainability.

 

Lets have a look for simple Example with jUnit:

Condition : expected = actual

LearnAssertions.java

package myWorkjUnit;

import junit.framework.Assert;

import org.junit.Test;

public class LearnAssertions {

@Test
 public void testAdvertisingPrograms(){
 System.out.println("open browser and go to URL");
 System.out.println("click on link");
 System.out.println("click on one Login link");

 String actual = "actual";
 String expected = "actual";

// if("ElementLocation" == "ElementLocation from above statement"){
// System.out.println("Pass");
// }else{
// System.out.println("fail");
// report Error
// }


 Assert.assertEquals(expected, actual);

 }

}

Condition : expected != actual

package myWorkjUnit;

import junit.framework.Assert;

import org.junit.Test;

public class LearnAssertions {

@Test
 public void testAdvertisingPrograms(){
 System.out.println("open browser and go to URL");
 System.out.println("click on link");
 System.out.println("click on one Login link");

 String actual = "actual";
 String expected = "expected";

// if("ElementLocation" == "ElementLocation from above statement"){
// System.out.println("Pass");
// }else{
// System.out.println("fail");
// report Error
// }


 Assert.assertEquals(expected, actual);

 }

}

Skip all testcase for specific Class using Assume.assumeTrue() using jUnit

package myWorkjUnit;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assume;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;

public class LearnAfterBefore {
 public static boolean checkThisBeforeRunThisClass(){
// return true;
 return false;
 }


 @BeforeClass
 public static void testLoadConfiguration(){
 System.out.println(&quot;Load configuration files&quot;);
 System.out.println(&quot;initilize Excel files object&quot;);

 Assume.assumeTrue(checkThisBeforeRunThisClass());
 }

 @Before
 public void testsetUp() {
 System.out.println(&quot;Open browser&quot;);
 System.out.println(&quot;Navigate URL&quot;);

 }

 @Ignore
 @Test
 public void testAdvancedSearch() {
 System.out.println(&quot;Search on website&quot;);
 }


 @Test
 public void testVerifySearchResult(){
 System.out.println(&quot;Verify search result&quot;);
 }



 @After
 public void testtearDown() {
 System.out.println(&quot;Close Browser&quot;);
 }

 @AfterClass
 public static void testReportResult(){
 System.out.println(&quot;Report result&quot;);
 }

}

Skip all testcase for specific Class using Assume.assumeTrue() using jUnit

Skip all testcase for specific Class using Assume.assumeTrue() using jUnit

Reference : Assume (JUnit API)

How To Group Multiple Test Classes into a Suite using @runwith(suite.class) junit?

The “Suite Test” means bundle a few unit test cases and run it together.

Lets consider following 2 classes we want to execute in a Group
firstjunitprogram.java
LearnAfterBefore.java

Make following new class
JUnitSuiteTest.java

and Write following stuff into it and check out the results.

package myWorkjUnit;

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

@RunWith(Suite.class)
@Suite.SuiteClasses({ firstjunitprogram.class,LearnAfterBefore.class })
public class JUnitSuiteTest {

}

suite.class

suite.class

firstjunitprogram.java

package myWorkjUnit;

import org.junit.Test;

public class firstjunitprogram {
 @Test
 public void Divide() {
 System.out.println("Result - " + divide(10, 5));

 }

 @Test
 public void substraction(){
 System.out.println("Result - " + substraction(10, 5));
 }

 @Test
 public void Addition(){
 System.out.println("Result - " + addition(10, 5));
 }

 public int divide(int x, int y) {
 return x / y;

 }

 public int addition(int x, int y) {
 return (x+y);

 }

 public int substraction(int x, int y) {
 return (x-y);

 }

}

LearnAfterBefore.java

package myWorkjUnit;

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

public class LearnAfterBefore {
 @BeforeClass
 public static void testLoadConfiguration(){
 System.out.println("Load configuration files");
 System.out.println("initilize Excel files object");
 }

 @Before
 public void testsetUp() {
 System.out.println("Open browser");
 System.out.println("Navigate URL");

 }

 @Ignore
 @Test
 public void testAdvancedSearch() {
 System.out.println("Search on website");
 }

 @Test
 public void testVerifySearchResult(){
 System.out.println("Verify search result");
 }

 @After
 public void testtearDown() {
 System.out.println("Close Browser");
 }

 @AfterClass
 public static void testReportResult(){
 System.out.println("Report result");
 }
}

Reference Link 1

how to ignore test cases in junit? / how to use @ignore in junit?

Sometimes it happens that our code is not ready and test case written to test that method/code will fail if run. The @Ignore annotation helps in this regards.

  • A test method annotated with @Ignore will not be executed.
  • If a test class is annotated with @Ignore then none of its test methods will be executed.
    package myWorkjUnit;
    
    import org.junit.After;
    import org.junit.AfterClass;
    import org.junit.Before;
    import org.junit.BeforeClass;
    import org.junit.Ignore;
    import org.junit.Test;
    
    public class LearnAfterBefore {
     @BeforeClass
     public static void testLoadConfiguration(){
     System.out.println("Load configuration files");
     System.out.println("initilize Excel files object");
     }
    
     @Before
     public void testsetUp() {
     System.out.println("Open browser");
     System.out.println("Navigate URL");
    
     }
    
     @Ignore
     @Test
     public void testAdvancedSearch() {
     System.out.println("Search on website");
     }
    
     @Test
     public void testVerifySearchResult(){
     System.out.println("Verify search result");
     }
    
     @After
     public void testtearDown() {
     System.out.println("Close Browser");
     }
    
     @AfterClass
     public static void testReportResult(){
     System.out.println("Report result");
     }
    }
    
    

     

     

     

    Reference Link 1 Link 2

Example for @BeforeClass – BeforeClass (JUnit API) and @AfterClass – AfterClass (JUnit API)

@BeforeClass
Run before all the tests in a class (Runs once for all of the tests)
Will execute the method once, before the start of all tests. This can be used to perform time intensive activities, for example to connect to a database.

@AfterClass
Will execute the method once, after all tests have finished. This can be used to perform clean-up activities, for example to disconnect from a database.

Run after all the tests in a class (Runs once for all of the tests)

package myWorkjUnit;

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

public class LearnAfterBefore {
 @BeforeClass
 public static void testLoadConfiguration(){
 System.out.println("Load configuration files");
 System.out.println("initilize Excel files object");
 }

 @Before
 public void testsetUp() {
 System.out.println("Open browser");
 System.out.println("Navigate URL");

 }

@Test
 public void testAdvancedSearch() {
 System.out.println("Search on website");
 }

 @Test
 public void testVerifySearchResult(){
 System.out.println("Verify search result");
 }

 @After
 public void testtearDown() {
 System.out.println("Close Browser");
 }

 @AfterClass
 public static void testReportResult(){
 System.out.println("Report result");
 }
}

Reference

BeforeClass (JUnit API)

AfterClass (JUnit API)

how to use @before in junit? Before (JUnit API) / how to use @after in junit After (JUnit API)

@Before

Will execute the method before each test. This method can prepare the test environment (e.g. read input data, initialize the class).
Run before each test method is run i.e. do a setup

@After
Run after each test method is run i.e. do a teardown
Will execute the method after each test. This method can cleanup the test environment (e.g. delete temporary data, restore defaults).

package myWorkjUnit;

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

public class LearnAfterBefore {
 @Before
 public void setUp() {
 System.out.println("Open browser");
 System.out.println("Navigate URL");

 }

@Test
 public void testAdvancedSearch() {
 System.out.println("Search on website");
 }


 @Test
 public void testVerifySearchResult(){
 System.out.println("Verify search result");
 }



 @After
 public void tearDown() {
 System.out.println("Close Browser");
 }

}

Reference

Before (JUnit API)

After (JUnit API)

Pupunzi

For a better web

Tech

News and reviews from the world of gadgets, gear, apps and the web

VentureBeat

News About Tech, Money and Innovation

Digital Inspiration

Tips and tutorials around all things tech.

Thinkwareglobal's Blog

Just another WordPress.com weblog

Kenazari's Blog

Just another WordPress.com weblog

Richfowler1's Blog

Just another WordPress.com weblog

Romaicus's Blog

Just another WordPress.com weblog

botlaguduri

Just another WordPress.com site

chandanag89

Just another WordPress.com site

meghshetty

Just another WordPress.com site

digitalmediaexpert

digital media expert blog

Thinking in Silverlight

Silverlight/WPF/Windows 8 Store App

Different Journeys

Let's make life easier!

LAW RESOURCE INDIA

LEGAL RESOURCE CENTRE / COURT JUDGMENTS / LEGAL ARCHIVES

BookConnect

Promoting Indian language Books

Actively Lazy

Software, crafted with passion

SAPonPower

An ongoing discussion about SAP infrastructure

SAP Career

Your Career Mentor

hrsapcertification

Just another WordPress.com site

The secret product manager

Thoughts about product management, SUSE, Linux, ARM processors, Cloud, AIX, Power Systems, and other things that interest me

Sap Certification Material . Com

Quality store for sap software and courses

Simon Les Flex's Blog

SAP Process Integration Specialist - NOW WE CAN DO BETTER!

Oracle Technologies Primer

An Oracle Fusion Middleware and iPaaS blog!

Gilberto Holms

Java, Middleware, SOA Architecture Blog

The Skeleton

Java code skeletons, tips and pointers

J@n van Zoggel

integration, innovation & random technology stuff

The Pragmatic Integrator

Hints and tips from a pragmatic integration specialist

briskwalk

The pace of life..

Optimalbg's Blog

Just another WordPress.com site

IT Jobs in USA

Keep the track of this Blog if you are looking out for some good Opportunities to work in USA....

Referral Jobs | Right Place to Get a Job

Hurry you are one Click away to get a job - Fresher Jobs for 2012, 2013 fresher’s and also high paid jobs for well Experienced IT professionals on Referal jobs.

eccinternational.wordpress.com/

ISO Consulting | ISO 27001 | ISO 20000 | CMMI | BCM | GRI Sustainability Reporting & Assurance | eLearning | Trainings | Philippines

Michael Korn's Blog

Musings on Life, Career, Faith and Technology

WORKINGWITHQTP

Just another WordPress.com weblog

Solutions365

.net, WCF, Unity, IOC, SQL

SQA and Testers Blog

Just another WordPress.com weblog

Expertqtp's Weblog

Just another WordPress.com weblog

Sai Chamarthi

Experienced Testing Professional

saxenavinay

A great WordPress.com site

Suresh4qtp's Blog

Just another WordPress.com site

jonah95hill

This WordPress.com site is the cat’s pajamas

It's always something...

Just another WordPress.com weblog

Faculty of Information Technology - Lê Ngọc Tiến

Be Yourself! Simplify Our Goals! Nothing is Impossible!

Anti-Malware Testing

Thoughts on security product testing past and present

Methods & Tools

Practical knowledge for the software developer, tester and project manager