Showing posts with label Junit. Show all posts
Showing posts with label Junit. Show all posts

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.

Tuesday 15 March 2016

Configure JUnit Testing Framework with Eclipse

Hi everyone this is going to be very short and simple. We are going to configure our Eclipse project to write and run our test cases with Junit framework. Junit is very commonly used testing framework and if you don not want to use Junit then you can also go with TestNG framework. In this post we will focus of Junit.

It is just simple 2 minutes job to configure Junit if you follow below steps -
1. Right Click on you project in eclipse.
2. Click on Properties -> Build Path -> Add Libraries


3. Select Junit and Click Next


4. Select Junit4 and Click Finish