Testing with Junit4

Post on 28-Nov-2014

436 views 0 download

description

Introduction to Junit4

Transcript of Testing with Junit4

1

Testing with JUnit 4

What is JUnit ?• JUnit is a Regression Testing Framework* for the

Java Programming Language. • One of a family of unit testing frameworks

collectively known as xUnit.• Open source framework

*One of the main reasons for regression testing is to determine whether a change in one part of the software affects other parts of the software

Features

•Provides Annotation to identify the test methods.

•Provides Assertions for testing expected results.

•Provides Test runners for running tests.

4

Coding Conventionso Name of the test class end with "Test".o Name of the method begin with "test".o Return type of a test method must be

void.o Test method must not throw any

exception.o Test method must not have any

parameter.

Simple Testpublic class FooTest {

@Test public void testMultiply() { MyClass tester = new MyClass();

// Tests assertEquals("10 x 0 must be 0", 0, tester.multiply(10, 0)); assertEquals("0 x 10 must be 0", 0, tester.multiply(0, 10)); assertEquals("0 x 0 must be 0", 0, tester.multiply(0, 0)); }

}

Component of JUnit

•JUnit test framework provides following important features/component

oFixturesoAssertions (provides Assert API)oTest suites (TestSuite API)oJUnit classes

7

Fixtures • Fixtures is a fixed state of a set of objects used as a

baseline for running tests. The purpose of a test fixture is to ensure that there is a well known and fixed environment in which tests are run so that results are repeatable.

- Usage - o Preparation of input data and setup/creation of fake

or mock objectso Loading a database with a specific, known set of datao Copying a specific known set of files creating a test

fixture will create a set of objects initialized to certain states.

8

Assert

public class Assert extends java.lang.Object

• This class provides a set of assertion methods useful for writing tests. Only failed assertions are recorded.

• JUnit provides overloaded assertion methods for all primitive types and Objects and arrays (of primitives or Objects)

• If fail AssertionFailedError

Assert Methods

11

Test Suite

•Test suite means bundle a few unit test cases and run it together. In JUnit, both @RunWith and @Suite annotation are used to run the suite test.

TestSuite Example

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

@RunWith(Suite.class)@Suite.SuiteClasses({ TestFeatureLogin.class,

TestFeatureLogout.class, TestFeatureNavigate.class, TestFeatureUpdate.class

})

public class FeatureTestSuite { // the class remains empty, // used only as a holder for the above annotations}

Test execution order• JUnit does not specify the execution order of test method

invocations• From version 4.11, JUnit will by default use a deterministic,

but not predictable, order (MethodSorters.DEFAULT)

• @FixMethodOrder(MethoSorters.JVM): Leaves the test methods in the order returned by the JVM. This order may vary from run to run.

• @FixMethodOrder(MethodSorters.NAME_ASCENDING): Sorts the test methods by method name, in lexicographic order.

Some More Features

Ignore Test

•Sometimes it happens that our code is not ready and test case written to test that method/code will fail if run or we just don’t want to test that test case at that moment. The @Ignore annotation helps in this regards.

oA test method annotated with @Ignore will not be executed.

o If a test class is annotated with @Ignore then all of its test methods will be ignored.

Ignored Test Exampleimport org.junit.Ignore;import org.junit.Test;

@Ignorepublic class IgnoreTest {

@Testpublic void notIgnored(){

System.out.println("this is executed");}

@Ignore@Testpublic void itIsIgnored(){

System.out.println("This test is ignored");}}

Time test

• Junit provides a handy option of Timeout. If a test case takes more time than specified number of milliseconds then Junit will automatically mark it as failed. The timeout parameter is used along with @Test annotation.

Time Test xampleimport org.junit.Test;

public class TimeTest {@Test(timeout=10)public void testTime(){for(int i=0;i<1000;i++){System.out.println("hiiiiii");}}}

Exception Test

•Junit provides a option of tracing the Exception handling of code. You can test the code whether code throws desired exception or not. The expected parameter is used along with @Test annotation.

Exception Test Exampleimport org.junit.Test;public class ExceptionTest {

@Test(expected=ArithmeticException.class)public void exception() {

int s=12/0;}

}

Parameterized Test• Junit 4 has introduced a new feature Parameterized

tests.Parameterized tests allow developer to run the same test over and over again using different values. There are five steps, that you need to follow to create Parameterized tests.

o Annotate test class with @RunWith(Parameterized.class)o Create a public static method annotated with @Parameters that

returns a Collection of Objects (as Array) as test data set.o Create a public constructor that takes in what is equivalent to

one "row" of test data.o Create an instance variable for each "column" of test data.o Create your tests case(s) using the instance variables as the

source of the test data.

Parameterized Test Example

executed three times

Rules

•Via the @Rule annotation you can create objects which can be used and configured in your test methods.

•This adds more flexibility to your tests. •Testers can reuse or extend one of the

provided Rules ,or write their own.

Rule sample

More RulesTemporaryFolder The TemporaryFolder Rule allows creation of

files and folders that are guaranteed to be deleted when the test method finishes (whether it passes or fails):

Timeout The Timeout Rule applies the same timeout to all test methods in a class

TestName The TestName Rule makes the current test name available inside test methods

ErrorCollector The ErrorCollector rule allows execution of a test to continue after the first problem is found (for example, to collect _all_ the incorrect rows in a table, and report them all at once):

ExpectedException The ExpectedException Rule allows in-test specification of expected exception types and messages:

Categories

•From a given set of test classes, the Categories runner runs only the classes and methods that are annotated with either the category given with the @IncludeCategory annotation, or a subtype of that category