Saturday, March 12, 2016

Java : Looping (Iterator)

Looping (Iterator)

 

Iterator :

Collections = Lists(arraylist) , Set(HashSet -remove duplicates) , Map(similar to dictionary)
  1. Java iterator is an interface.
  2. belongs to collection framework
  3. allow us to traverse the the data element without bothering implementation. Ex : User may use array ,list etc.,
  4. Basically List and set collection provides the iterator ( ArrayList, LinkedList, and TreeSet etc)
  5. Map implementation such as HashMap doesn’t provide Iterator directly


Using Iterator

  1. Create an  iterator
  2. Have the loop iterate as long as hasNext( ) returns true.
  3. Within the loop, obtain each element by calling next( ).


Array List
ArrayList<Student> s= new ArrayList<Student>();   
s.add(new Student(Adam,98));    
s.add(new Student(Bob,65));           

for(int i=0;i<=s.size();i++)                //Noraml Loop
    System.out.println(s.get(i).name); 

for(Student s_loop:s)                          //Enhanced Loop                           
    System.out.println(s_loop.name);  

for (Iterator i=s.iterator();s.hasnext()){    //Iterator
    Student s_loop=(Student)i.next();
    System.out.println(s_loop.name);
    }

   
Array
Student[] s =new Student[2];
Student Adam=new Student("Adam",98);
Student Bob=new Student("Bob",67);

s[0]=Adam;
s[1]=Bob;

for(int i=0;i<=s.length-1;i++)
    Syste
m.out.println(s[i].name);


   
You can use Iterator Patten when you want similar implementation in both List and Array
1. ArrayList already comes ready with iterator so need to worry about that
2. We need to implement for Array or Class which uses array without changing the code.
(326pg -Design Patterns,Head First)
Or
1. Use Guava
Iterator<String> it = Iterators.forArray(array);
 

Examples :

1.  HashMap

//Use Java 1.8
HashMap m=new HashMap();
m.put(1, "01");
m.put(2, "02");

m.forEach( (k,v) -> System.out.println("Key: " + k + ": Value: " + v));


or 
Iterator entries = myMap.entrySet().iterator();
while (entries.hasNext()) {
  Entry thisEntry = (Entry) entries.next();
  Object key = thisEntry.getKey();
  Object value = thisEntry.getValue();
  // ...
}


 2. Array List
ArrayList a=new ArrayList();   
a.add(1);
a.add("hi");

Iterator it=a.iterator();
while(it.hasNext()){
System.out.println(it.next());
}


3.HashSet
HashSet s=new HashSet();
s.add("hi");
s.add("hi");
s.add("abc");
s.add("bye");

Iterator i=s.iterator();
while(i.hasNext())
{
System.out.println(i.next());
}


Example 2


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

List<String> crunchifyList = new ArrayList<String>();

crunchifyList.add("eBay");
crunchifyList.add("Paypal");
crunchifyList.add("Google");
crunchifyList.add("Yahoo");
// iterate via "for loop"
for (int i = 0; i < crunchifyList.size(); i++) {
System.out.println(crunchifyList.get(i));
}
// iterate via "New way to loop"
for (String temp : crunchifyList) {
System.out.println(temp);
}
// iterate via "iterator loop"
Iterator<String> crunchifyIterator = crunchifyList.iterator();
while (crunchifyIterator.hasNext()) {
System.out.println(crunchifyIterator.next());
}
// iterate via "while loop"
int i = 0;
while (i < crunchifyList.size()) {
System.out.println(crunchifyList.get(i));
i++;
}
// collection stream() util: Returns a sequential Stream with this collection as its source
crunchifyList.forEach((temp) -> {
System.out.println(temp);
});
}
}

Thursday, March 10, 2016

TestNg: @BeforeTest

@BeforeTest



BeforeTest execution = No of times you have defines <test name>.Below example you have used <test name> twice therefore Beforetest excutes twice













import org.testng.annotations.*;

public class testng_annotations {
   
    @BeforeSuite
    public void Beforesuite(){
        System.out.println("beforesuite");       
    }
   
    @BeforeTest
    public void Beforetest(){
        System.out.println("beforetest");
    }
   
    @DataProvider
    public Object[][] dataprovider(){
        Object[][] obj=new Object[2][2];
        obj[0][0]=1;
        obj[1][0]=2;
        obj[0][1]=3;
        obj[1][1]=4;
        return obj;
    }
   
    @Test(dataProvider="dataprovider")
    public void test(int i,int y) {   
            System.out.println("Data " + i+y);// execute 2nd       
    }
}

 

 Result

 

Wednesday, March 9, 2016

TestNg : Loop testcases logic (Reflection and ITestContext)

Loop testcases logic (Reflection and ITestContext)


Code Below :

public class BeforeMethodParametersExample {
    private Method method;
    private ITestContext context;
    private static final Object[][] DATA1 = { new Object[] { "first" },new Object[] { "second" }, };
    private int i;
   
    @DataProvider
    public Object[][] data1() {
        i=i+1;
        System.out.println("data provider "+1); //executes 1st
        return DATA1;//first , second
    }   
   
    //Method java.lang.reflect.Method;   ITestContext
//executes 2nd   
@BeforeMethod
    public void before(Method m, ITestContext ctx) {
        method = m;
        context = ctx;
        i=i+1;
        System.out.println("Name of test is " + method.getName()+" "+i); // execute 1st
    }
   
    @BeforeMethod  // -3rd
    public void beforeWithData(Object[] data) {
        for (Object o : data) {
            i=i+1;
            System.out.println("Data " + o+" "+i);// execute 2nd
        }
    }

    @Test(dataProvider="data1")  //4th
    public void someTest(String data) {
        i=i+1;
        System.out.println("Name of test is " + method.getName()+" "+i);
        System.out.println("Suite name is " + context.getSuite().getName()+" "+i);
    }
   
}

Java : Run As > TestNg option not available

 Run As > TestNg option not available

 

  1. Open Eclipse
  2. Help >MarketPlace
  3. search for "Testng" 
  4.  Install "Testng for Eclipse"
  5. Click on Install now 
  6. Restart Eclipse
  7. try again

Gradle : Using gradle in Command prompt

Using gradle in Command prompt

Make sure Gradle is setup in your system environment variables


Downloading with Git using Windows CMD from a GitHub project
You can get download the link from GitHub <b>HTTPS clone URL</b>
Download with Window Command Prompt cmd for above picture HTTPS clone URL


  1.  Copy the HTTPS clone URL shown in picture 1
  2. Open CMD
  3. git clone //paste the URL show in picture 2
  4. or you can just click on button "Clone in desktop" or "Download ZIP"

Running Gradle tests
  1. In cmd prompt > Goto the downloaded directory
  2. gradle clean
  3. gradle builddependents
  4. gradle