Thursday 29 September 2016

Record Test Cases using Espresso Test Recorder



Hi everyone it gives me immense pleasure to share with all that Android Studio 2.2 has been launched and as Android App Tester there is something very useful has been launched for us that is Espresso Test Recorder. In our Espresso Tutorials we have seen how to code and run Espresso test cases plus we have studied writing test cases for WebViews and Intents and much more. 

In this post I want to share with you about newly launched Android's Espresso Test Recorder and how we can us it effectively to record and run our test cases. If you are a Manual Tester and not comfortable then you must learn this as it is very simple and quick to learn feature of Espresso. If you are Automation Tester and already using Espresso should must try it out it will reduce you work load and helps you in faster test case development.

Video Tutorial is Also Available - 

 

What is Espresso Test Recorder ?

Espresso is Android's Instrumentation Test Framework which allows developers and testers to write UI test cases to test functionality of the app. Espresso Test Recorder is new feature introduced in Android Studio 2.2 which allows user to Manually perform steps in an device and add assertions to record test cases. 

Pros of Espresso Test Recorder -
1. Allow Us to create effective UI based Test Cases with user interactions.
2.We can capture assertions and interactions without accessing app's structure directly which increases execution speed and optimizes test case.
3.It saves lot of time to search for locators and then writing test cases.
4. It supports multiple assertions making more reliable test cases.
Cons of Espresso Test Recorder -
1. Currently does not Support Recording of WebViews interactions.
2.  Once We complete Recording once for next time Recording it launches the app there is no API to control such behavior.
3. Cannot record Assertions for Toast Messages

Step by Step Recording first Espresso Test Case -

Pre-requisite
1. Android Studio 2.2
2. Java 8
3. Environmental variable Set up for JAVA_HOME and Android_HOME

Mobile Device Settings
1. Go to Phone's Settings
2. Developers option
3. Turn off Windows Animator Scale, Transition Animator Scale & Animation Duration Scale.



Recording UI Interactions
1. Launch Android Studio 
2. Click on Start New Android Studio Project
3. Give Application Name as EspressoTestRecorder
4. Click on Next


5. Click on Next


6. Select Blank Activity and click on Next


7. Your Android Project will be opened
8. Go to Run -> Record Espresso Test 


9. Select a Device and click on OK
10. Check your device it will say "Waiting for Debugger" after installing the application when the window closes (Do not click on Force Close) start performing Tap and Type Events on the Mobile Application.


Record Assertions
1. Click on Add Assertions
2. It will take Screenshot of the Device and display it on the screen.


3. In Edit Assertions Section you can select what type of assertions you want to add.


4. Click on Save Assertions.
5. Then Click on Complete Recording to save your test case

Save The Test Case
1. A popup will appear with Name of the Activity on which test is recorded you can edit the name
2. Click on Save


3. The test case will be saved in Android ->app->package name with (androidTest)->TestClassName

Run the Test Case
1. Once you locate the Test Class right click on the name
2. Click on Run.




Isn't it simple and interesting to learn. Write your queries and questions in the comment section and spread the word about New Espresso Test Recorder to Ease work load. Happy Testing :-)



Monday 12 September 2016

JUnit Categories

JUnit Categories are only applicable for JUnit 4.8 and above. In this java interfaces are used to make different categories and add your test cases in different categories. This allows you to run your test cases as per different categories.

Whenever we are creating a automation framework. We write all the test cases  covering the entire application but at the time execution we realize that we want to run some test cases during Feature Testing, Some test cases while User Acceptance Testing and some test cases during production release so in this case you can categories your test case and execute as per categories.

Let us see an example of JUnit categories as shown below -



public interface FastTests 
{ 
/* category created */
}

public interface SlowTests
 {
 /* category created */
}

public class A {
        @Test
        public void a() {
                fail();
        }

        @Category(Feature1Tests.class)
        @Test
        public void b() {
        }
}

@Category({ Feature1Tests.class, Feature2Tests.class })
public class B {
        @Test
        public void c() {
        }
}

@RunWith(Categories.class)
@IncludeCategory(Feature1Tests.class)
@SuiteClasses({ A.class, B.class })
// Note that Categories is a kind of Suite
public class Feature1TestSuite {
        // Will run A.b and B.c, but not A.a
}

@RunWith(Categories.class)
@IncludeCategory(Feature1Tests.class)
@ExcludeCategory(Feature2Tests.class)
@SuiteClasses({ A.class, B.class })
// Note that Categories is a kind of Suite
public class Feature1TestSuite {
        // Will run A.b, but not A.a or B.c
}

Junit Parameterized Tests

Junit Testing framework allows us to use Parameters in out Test Class. To write Parameterized test case the Test Class should contain only one test case and we can provide multiple parameters for it as per given in our example below.

To notify that the particular class as parameterized test add annotation 
@RunWith(Parameterized.class) 

Such class need a static method with annotation @Parameters annotation. This method generates collection of arrays and each item in the collection is refereed as array. We can also use @Parameter annotation on public fields and inject test values in the test.

Let us see the following example to understand how to make use of Parameterized Junit Tests  -


import static org.junit.Assert.assertEquals;

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;

@RunWith(Parameterized.class)
public class ParameterizedTestUsingConstructor {

    private int num1;
    private int num2;

    public ParameterizedTestUsingConstructor(int p1, int p2) {
        num1 = p1;
        num2 = p2;
    }

    // creates the test data
    @Parameters
    public static Collection<Object[]> data() {
        Object[][] data = new Object[][] { { 1 , 2 }, { 5, 3 }, { 121, 4 } };
        return Arrays.asList(data);
    }


    @Test
    public void testMultiplyException() {
        MyClass tester = new MyClass();
        assertEquals("Result", num1 + num2, tester.add(num1, num2));
    }


    // class to be tested
    class MyClass {
        public int add(int i, int j) {
            return i + j;
        }
    }

}

The test case executes 3 times as per configured data set.



Installation of Junit with Maven

As we have seen that we can use Junit with any Maven project now let us learn that how to use it with Maven. 

Consider you have a Mane Project. Then open your project's Pom.xml file and copy the below code.


<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
</dependency>

Once the code is copied you can go to command line and navigate to your project directory
execute command  mvn clean and mvn compile and check that build is successful this means you are good to go. 

This blog post is for people using Maven project. So I have not added details of what is Maven and how to install Maven .

Junit Test Suits and Test Execution Order


When you have large number test classes and you want to combine then and manage them the you can create a Test Suit. Execution of test case means execution of all test classes inside the Suite as per specified order.

The following example gives outline of Suit class. It contains 3 test classes FirstTestClass and SecondTestClass. You can add as many test classes as you want.

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

@RunWith(Suite.class)
@SuiteClasses({
                FirstTestClass.class,
                SecondTestClass.class,
                ThirdTestClass.class })

public class AllTests {

}   

Test Execution Order within Class - Junit Assumes that the test cases written inside class and independent and can be executed randomly.  But in case if you have to define the flow of Junit test cases within a class then there is annotations @FixMethodOrder which you can use. Consider below example with Class MyTests with Test Cases BTest(), ATest() and CTest() and we can define the order of execution as per method name ascending order alphabetically.

In following example the order of execution will be  -
1. ATest()
2. BTest()
3. CTest()



@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class MyTests {

@Test
public void BTest()
{
}

@Test
public void ATest()
{
}

@Test
public void CTest()
{
}

}

Junit Assert Statements

As we all know that test case is incomplete without assertions. Assertions means checking expected result matches actual result that is always final step of any test case. So JUnit testing framework provides us way to automate our assertions in simple and effective way.

Junit Provides Assert Class with some assert methods which we can use write our own assert statements.It allows us to specify error message with expected and actual result so that we can understand the why the test case failed.

The Assert Statement compare actual result with Expected result and if the comparison fails then it throws AssertionException.

Let us see some commonly used assertions example  -

1. assertTrue([message,] boolean condition) - Checks that the boolean condition is true.
2. assertFalse([message,] boolean condition) - Checks that the boolean condition is false.
3. assertEquals([message,] expected, actual) - Tests that two values are the same. Note: for arrays the reference is checked not the content of the arrays. 
4. assertEquals([message,] expected, actual, tolerance) - Test that float or double values match. The tolerance is the number of decimals which must be the same.
4. assertNull([message,] object) - Checks that the object is null. 
 
 
Whenever you start writing test cases you can explore more more just by Typeing Assert.(cltr+space) the you will see the lis of methods provided by Assert class and you can use them to make your test cases more and more effective.
 
 If you have any questions then you can put it in comments.











Saturday 10 September 2016

What is Junit Annotations ?

Junit Annotations are very useful for defining the flow of executions and identification of test methods. These Annotations are used with class and method and it gives additional meaning to the method and class indicating its behavior are flow of executions. For example @Test annotations is used with any Java method and now the java method is identified as a Test Case and it will execute as a Test Case and not like ordinary Java Method. Similarly there are few Basic Junit Annotations which are very important and widely used by Automation Tester.

Consider below Sample Code Example - 
The below code skeleton makes use of Basic Junit Annotations. In below class there are total 6 methods out of which 2 are test cases. Let us see in more details about each annotations.


Public void TestClass
{

@BeforeClass
public void startUp()
{
 your code
}

@Before
public void setUpTest()
{
Your Code
}

@Test
public void firstTest()
{
Your Code
}

@Test
public void secondTest()
{
Your Code
}

@After
public void teatDownTest()
{
Your Code
}

@AfterClass
public void End()
{
Your Code
}

}


@BeforeClass  - In above example this annotations is used for startUp() method indications that as soon as class starts its execution the method with @BeforeClass Annotation will execute first. Any logic which you want to execute first before execution of any other method and test case in the class then add that logic in startUp() method with @BeforeClass Annotation.

@Before - Any method marked with  @Before annotation will execute once before each test case execution. This means setUpTest() method in above execution will execute two times before firstTest() and secondTest(). Any logic which you want to execute before each test case such as launching application etc we need to write it using @Before Annotation.

@Test -  This annotation define that execute firstTest() and secondTest() method as Test Case and not as Method in Java Class.

@After - Any method marked with  @After annotation will execute once After each test case execution. This means tearDownTest() method in above execution will execute two times after firstTest() and secondTest(). Any logic which you want to execute after each test case such as closing the application etc we need to write it using @After Annotation.
@AfterClass - In above example this annotations is used for End() method indications that as soon as all the test cases in class finish execution the method with @AfterClass Annotation will execute. Any logic which you want to execute first at the end of execution of all test cases in the class then add that logic in End() method with @AfterClass Annotation.


The Complete Flow of Executions As per Above Example -

1. startUp()
2. setUpTest()
3. firstTest()
4. teardownTest()
5. setUpTest()
6. secondTest()
7. tearDownTest()
8. End()


How to Configure Junit with Android Studio

We have seen how to Install and create a project in Android Studio. Before starting automation testing we need to configure Junit Testing framework with Android Studio. Junit Testing Framework helps us define flow of execution. Let us learn more about Junit.

What is Junit?

Junit is widely used testing framework along with Java Programming Language. You can use this automation framework for both unit testing and UI testing.It helps us define the flow of execution of our code with different Annotations. Junit is built on idea of "first testing and then coding" which helps us to increase productivity of test cases and stability of the code.

Important Features of Junit Testing - 

1. It is open source testing framework allowing users to write and run test cases effectively.
2. Provides various types of annotations to identify test methods.
3. Provides different Types of Assertions  to verify the results of test case execution.
4. It also gives test runners for running tests effectively.
5. It is very simple and hence saves time.
6. It provides ways to organize your test cases in form of test suits.
7. It gives test case results in simple and elegant way.
8. You can integrate Jnuit with Eclipse ,Android Studio,Maven & Ant

Junit With Android Studio

1. Create a new Android Studio Project or Open your existing project.
2. Go to App -> Build.gradle.



3. In the file add the line of code as shown in below screenshot.


4. click on sync.


5. Once you get Buid Successful Message then your Junit Setup is ready for use.