Showing posts with label SDET. Show all posts
Showing posts with label SDET. Show all posts

Saturday, January 3, 2015

How to create logs in HTML formats using log4j

1)Create a project in Eclipse
2)Create a file - log4j.properties and paste the following content in it

# Define the root logger with file appender
log4j.rootLogger = DEBUG, HTML

# Define the file appender
log4j.appender.HTML=org.apache.log4j.FileAppender
log4j.appender.HTML.File=application.html

# Define the html layout for file appender
log4j.appender.HTML.layout=org.apache.log4j.HTMLLayout
log4j.appender.HTML.layout.Title=Application logs
log4j.appender.HTML.layout.LocationInfo=true
log4j.appender.HTML.Threshold=DEBUG

3)Create a sample class to log
(Make sure log4j jar file is added in the build path)

import org.apache.log4j.Logger;

public class log4j_and_html
{
    static Logger log = Logger.getLogger(log4j_and_html.class);

    public static void main(String[] args)
    {

        log.debug("Sample debug message");
        log.info("Sample info message");
        log.error("Sample error message");
        log.fatal("Sample fatal message");
    }
}

That's it, run the program and all logs will be created in HTML format


Saturday, August 30, 2014

Insertion Sort

import java.util.ArrayList;
import java.util.List;


public class Insertion_sort {

public static void insertion(int[] arr){

int temp;
System.out.println("Before sorting");
for(int a=0; a<arr.length; a++){
System.out.print(" "+arr[a]);
}

for(int i = 1; i<arr.length; i++) {

int value_to_sort = arr[i]; // Consider the second element to sort, since first element is considered to be sorted
int j = i; // have both i and j at second place
while(j>0 && arr[j-1]>value_to_sort){//while j>0 means first place is not reached, we need to continuously move it up the ladder
//arr[j-1]>value_to_sort, if first element is greater than the swap
arr[j] = arr[j-1];
j--;//the number right not be in the right place may be it is required to move further up, so decrement j and check
}
arr[j]= value_to_sort; // finally put the number in its place
}

System.out.println();
System.out.println("After sorting");
for(int a=0; a<arr.length; a++){

System.out.print(" "+arr[a]);
}

}

public static void main(String[] args) {

int[] arr = {10, 7, 1, 2, 4, 5};
insertion(arr);
}

}

Quick Sort

Sorting is one of the basic algorithms any SDET must know,
I'm sharing a popular and efficient Sorting algorithm, for you to add it up your sleeves

public class Quick_Sort {

public static void exchange(int[] arr, int index1, int index2){
int temp = arr[index1];
arr[index1] = arr[index2];
arr[index2] = temp;
}
public static void Quicksort(int[] arr, int low, int high) {


int i=low;
int j=high;
int pivot = arr[(i+j)/2];

//Divide the array into two parts
while(i<=j){

while(arr[i]<pivot){
i++;
}

while(arr[j]>pivot){
j--;
}

if(i<=j){
exchange(arr,i,j);
i++;
j--;

}

if(low<j){
Quicksort(arr,low, j);
}
if(i<high){
Quicksort(arr, i, high);
}
}

}

public static void printarray(int[] arr){
for(int i=0; i<arr.length; i++){

System.out.print(" "+arr[i]);
}
}

public static void main(String[] args) {

int[] arr = {10, 20, 2, 3, 24, 45, 100};
System.out.println();
System.out.println(" Before Sorting");
printarray(arr);
Quicksort(arr, 0, arr.length-1);
System.out.println();
System.out.println(" After Sorting");
printarray(arr);

}

Friday, August 29, 2014

JUnit - Parallel Testing

Running your tests in parallel is a powerful way to speed up your tests.
Good automated tests should be independent, isolated and reproducible, making them ideal candidates for being run concurrently
But in real world scenarios of web testing this hardly happens and when it does we must make use of JUnit parallel testing capability to speed up the testing

Example

@Test
public void Test1() {
System.out.println("In Test 1");
}

@Test
public void Test2() {
System.out.println("In Test 2");
}

@Test
public void Test3() {
System.out.println("In Test 3");
}

Runner class

@RunWith(ParallelSuite.class)
@SuiteClasses({Test1.class, Test2.class, Test3.class})
public class ABCSuite {}


Dependencies 

<dependency>
    <groupId>com.googlecode.junit-toolbox</groupId>
    <artifactId>junit-toolbox</artifactId>
    <version>2.0</version>
</dependency>

JUnit - Download and Install

Download the following jars file from http://search.maven.org/

junit.jar
hamcrest-core.jar

Maven Dependencies

JUnit

<dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>4.11</version>
  <scope>test</scope>
</dependency>

Hamcrest

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-parent</artifactId>
<version>1.3</version>
</parent>
<artifactId>hamcrest-core</artifactId>
<packaging>jar</packaging>
<name>Hamcrest Core</name>
<description>
This is the core API of hamcrest matcher framework to be used by third-party framework providers. This includes the a foundation set of matcher implementations for common operations.
</description>
</project>

JUnit Exception Testing

In Automation, it is not only important to check if screens behave as expected with correct data, it is also important to check if tests would throw exception when invalid/inappropriate data is given, this will make the Framework more robust

Lets see how JUnit allows us to do Excepton Testing

Example 1

new ArrayList<Object>().get(0); // Array list is empty, so it should result in IndexOutOfBoundsException

  @Test(expected= IndexOutOfBoundsException.class)
    public void empty() {
         new ArrayList<Object>().get(0);
    }
So this test case would pass, if IndexOutOfBoundsException is thrown else the Test case fails

Example 2

 @Test
    public void testExceptionMessage() {
        try {
            new ArrayList<Object>().get(0);
            fail("Expected an IndexOutOfBoundsException to be thrown");
}

         catch (IndexOutOfBoundsException anIndexOutOfBoundsException) {
            assertThat(anIndexOutOfBoundsException.getMessage(), is("Index: 0, Size: 0"));
            }
    }

In this way we can not only test what Exception we get but we can also validate what message is thrown 

JUnit Assertions

Assertions is one of the most used and important part of your Framework
JUnit provides overloaded Assertions for all primitive types(ie int, string etc), Objects and Arrays(Primitive and Objects)

Syntax for Assertions
<expected_value> , <actual_value>
or
<String output for failure>, <expected_value> , <actual_value>

Examples

1)Compares if text are same
 @Test
  public void testAssertEquals() {
    org.junit.Assert.assertEquals("failure - strings are not equal", "text", "text");
  }

2)Checks if condition passed results in false, if false_var is evaluated to true then error is shown
Remember this condition can be used to optionally run your test case, if you include this in your @Before Class

  @Test
  public void testAssertFalse() {
    org.junit.Assert.assertFalse("failure - should be false", false_var);
  }

3)Checks if the obect passed is null or not, if not null, then shows error
   @Test
  public void testAssertNotNull() {
    org.junit.Assert.assertNotNull("should not be null", new Object());
  }

4)Checks if two obects are same
  @Test
  public void testAssertNotSame() {
    org.junit.Assert.assertNotSame("should not be same Object", new Object(), new Object());
  }

A slightly different assertion is assertThat, usage is

Syntax
<optional_failure_msg> , <actual_value> , <matcher_Object>

asserThat is used in the suitations, where the actual value is dynamically generated and you can use a matcher obect to verify it at run time with a pattern

Examples

1) This can be used to check your order_num pattern, date etc
 @Test
  public void testAssertThatBothContainsString() {
    org.junit.Assert.assertThat("albumen", both(containsString("a")).and(containsString("b")));
  }

2)Checks the Array List

  @Test
  public void testAssertThatEveryItemContainsString() {
    org.junit.Assert.assertThat(Arrays.asList(new String[] { "fun", "ban", "net" }), everyItem(containsString("n")));
  }