Wednesday, March 16, 2016

Gradle : Debugging Gradle Project

Gradle : Debugging Gradle Project



Since my last Analysis I found fairly less information on Debugging Gradle in my line of work which is specifically on Automation .

So the most convenient way was Debug using TestNG rather than Gradle .As I prefer using TestNg as my Automation Framework over Junit so there will be Testng.xml in the project folder (or similar xml file ).


One can directly Start debugging  by :Rt ck on testng.xml > Debug As >TestNg


If you are getting any error make sure you do these.Assuming you are using Eclispe
  1. Make sure you have plugin TestNg installed to eclipse .If not then goto Help>Market Place>Enter "testng" and search.
  2. Select testNG for Eclipse and click on Install >Select all options > restart Eclipse after installing
  3. goto  Project (title bar) > Clean
  4. Rt ck on Project > Properties >Java Build Path>Add Library > Select TestNG >Ck on OK

Now user should be able to Debug for Gradle projects using Testng as well using Rt ck on testng.xml > Debug As >TestNg .



Java : Introduction to Guava Core Libaray

Java : Introduction to Guava Core Library

download Jar :http://mvnrepository.com/artifact/com.google.guava/guava

http://docs.guava-libraries.googlecode.com/git/javadoc/overview-summary.html
(Visit the above JavaDoc for more information  and usage . click on Frames to view complete classes)




 What Is Guava ?


-    Open Source libraries provided by Google
-    provides utility methods

Most Frequently Used Classes

1. Optional - facilitate the code to handle values as available or not available instead of checking null values.
2. Preconditions - provide static methods to check that a method or a constructor is invoked with proper parameters.
3. Ordering - multiple utility methods, multi-type sorting capability, etc
4. Objects - provides helper functions applicable to all objects such as equals, hashCode, etc.
5. Range - represents an interval or a sequence. It is used to get a set of numbers/ strings lying in a particular range.
6. Throwables - Static class provides utility methods related to Throwable interface.
7. Collections Utilities - Provides utility api for handling ArrayLists,Lists,Maps,Sets etc .,
8. String Utilities - Provides utility api for Strings.(Splitter ,Joiner, CaseFormats etc., are one of them)
9. Math Utilities - For performing Mathoperations

Tuesday, March 15, 2016

Java : Exceptions (try catch)


Java : Exceptions (try catch)



1. Creating and Catching an Exception
    public void crossFingers()
    (
        try{
            Object.takeRisk();
        ) catch (BadException ex) // "ex" can be any variable
            System. out.println ("Aaarqh! ") ;
            ex .printStackTrace () ;
        }
    }

    public void takeRisk () throws BadException {
        if (abandonAllHope) {
            throw new BadException();
        }
    }

---------------------
2. A finally block - runs regardless of an exception or even if the catch has a return statement
   
    try (
        turnOvenOn();
        x.bake () ;
    }catch (BakingException ex)
        ex.printStackTrace();
    }finally { //
runs regardless of an exception or even if the catch has a return statement        
turnOvenOff();
    }

   
3. Multiple try catch

    try {
        throw new IOException();
        }catch (FileNotFoundException f){
           
        }catch (IOException  e){
            System.out.println(e);     //output :     java.lang.NullPointerException
            e.printStackTrace;        //output :    java.io.IOException at package.Test.main(Test.java:74)
                                   
        }catch (Exception e){        //Catches all sorts of Exception should be placed LAST
                                    //If passed 1st any catch block belowing will be skipped
        }finally{
        }

       
4. Multiple catch Using OR (|)
        try {
        do something ;
        }catch (FileNotFoundException | IOException e){ //Catch executes when either of the 2 exception occur
       
        }

       
5. What you can do inside catch block ?
    -    e.printStackTrace()
    -    e.getmessage();
    -     log.error("Ops!", e); //Using logging framework like logback or log4j
    -     "USER CAN DO ANY OPERATIONS"
   
6. What is Throwable t ?
    -    In normal cases we should always catch sub-classes of Exception.
   
    Example :
        try {
        do something ;
        catch(throwable t){ //"throwable" is super class of exception
           
        }

   
   

Excel :Create Drop Down in Excel Sheet(Test Data) with colored font

Create Drop Down in Test Data with colored font


To add this drop-down list to a sheet, do the following:
  1. Create the list in cells A1:A4. ...
  2. Select cell E3. ...
  3. Choose Validation from the Data menu.
  4. Choose List from the Allow option's drop-down list. ...
  5. Click the Source control and drag to highlight the cells A1:A4. ...
  6. Make sure the In-Cell Dropdown option is checked. ...
  7. Click OK.
Color coding a drop-down list in Excel's 
    1) Create your drop down list in any cell using Data Validation with fields. e.g, Low, Medium,High
    2) Highlight the drop down cell.
    3) Select Conditional Formatting
    4) Select Highlight cell rules, more rules
    5) Select Format only cells that contain
    6) Change the value in the format only cells with: to Specific Text
    7) Enter the text field . e.g. Low
    Select Format tab.
    9) Select the Fill tab and select your colour e.g. Green.
    10) Click Ok

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