0% found this document useful (0 votes)
44 views10 pages

ST Lab 01 2

ST LAB 01 2

Uploaded by

Noor-Ul Ain
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views10 pages

ST Lab 01 2

ST LAB 01 2

Uploaded by

Noor-Ul Ain
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

SOFTWARE TESTING

Experiment 07
Introduction to white box testing using Junit in
eclipse
(Part 1)

CLO-1: Construct the experiments/projects of varying


complexities
CLO-2: Use modern tools to solve problems of varying
complexities in software testing.
CLO-3: Construct the projects of varying complexities using
different software testing techniques
CLO-4: Demonstrate a unique solution of problem under
discussion
JUnit ?
JUnit is a unit testing framework for the Java Programming Language. It is
important in the test driven development, and is one of a family of unit testing
frameworks collectively known as xUnit.

JUnit promotes the idea of "first testing then coding", which emphasis on setting up the
test data for a piece of code which can be tested first and then can be implemented. This
approach is like "test a little, code a little, test a little, code a little..." which increases
programmer productivity and stability of program code that reduces programmer stress
and the time spent on debugging.

1.1Features
• JUnit is an open source framework which is used for writing & running tests.
• Provides Annotation to identify the test methods.
• Provides Assertions for testing expected results.
• Provides Test runners for running tests.
• JUnit tests allow you to write code faster with increasing quality
• JUnit is elegantly simple. It is less complex & takes less time.
• JUnit tests can be run automatically and they check their own results and
provide immediate feedback. There's no need to manually go through a report of
test results.
• JUnit tests can be organized into test suites containing test cases and even
other test suites.
• Junit shows test progress in a bar that is green if test is going fine and it turns red
when a test fails.

1.2 What is a Unit Test Case ?


A Unit Test Case is a part of code which ensures that the another part of code (method)
works as expected. To achieve those desired results quickly, test framework is
required .JUnit is perfect unit test framework for java programming language.

A formal written test-case is characterized by a known input and by an expected


output, which is worked out before the test is executed. The known input should
test a precondition and the expected output should test a post condition.
1.3 JUnit Test Framework
JUnit is a Regression Testing Framework used by developers to implement unit
testing in Java and accelerate programming speed and increase the quality of code.
JUnit Framework can be easily integrated with either of the followings:

 Eclipse

 Ant

 Meaven

2-Using JUnit
2.1. Unit testing with JUnit
JUnit is a test framework which uses annotations to identify methods that specify a test.
Typically these test methods are contained in a class which is only used for testing. It is
typically called a Test class.

The following code shows a JUnit test method . It can be created via
File → New → JUnit → JUnit Test case.

@Test

public void testMultiply() {



// MyClass is tested

MyClass tester = new MyClass();



// check if multiply(10,5) returns 50

assertEquals("10 x 5 must be 50", 50, tester.multiply(10, 5));


}
JUnit assumes that all test methods can be executed in an arbitrary order. Therefore
tests should not depend on other tests.

To write a test with JUnit you annotate a method with the @org.junit.Test annotation
and use a method provided by JUnit to check the expected result of the code execution
versus the actual result.

You can use the Eclipse user interface to run the test, via right-click on the test class
and selecting Run→ Run As → JUnit Test. Outside of Eclipse you can use
org.junit.runner.JUnitCore class to run the test. You can also mark a test method in a
class and select to run the test. Only the selected method will be executed.
2.2. Available JUnit annotations
The following table gives an overview of the available annotations in
JUnit

Table 1. Annotations

Annotation Description

@Test The @Test annotation identifies a method as a test method.


public void method()

Fails, if the method does not throw the named exception.


@Test (expected = Exception.class)

@Test(timeout=100) Fails, if the method takes longer than 100 milliseconds.

This method is executed before each test. It is used to


@Before
prepare the test environment (e.g. read input data, initialize
public void method()
the class).

@After This method is executed after each test. It is used to cleanup


public void method() the test environment (e.g. delete temporary data, restore
defaults). It can also save memory by cleaning up expensive
memory structures.

This method is executed once, before the start of all tests. It


@BeforeClass is used to perform time intensive activities, for example to
public static void method() connect to a database. Methods annotated with this
annotation need to be defined as static to work with JUnit.

This method is executed once, after all tests have been


@AfterClass finished. It is used to perform clean-up activities, for
example to disconnect from a database. Methods annotated
public static void method() with this annotation need to be defined as static to work
with JUnit.

@Ignore Ignores the test method. This is useful when the underlying
code has been changed and the test case has not yet been
adapted. Or if the execution time of this test is too long to be
included.
2.3. Assert statements
JUnit provides static methods in the Assert class to test for certain conditions. These
assertion methods typically start with assert and allow you to specify the error
message, the expected and the actual result. An assertion method compares the actual
value returned by a test to the expected value, and throws an AssertionException if the
comparison test fails.

The following table gives an overview of these methods. Parameters in [] brackets are
optional.

Table 2. Test methods

Statement Description

fail(String) Let the method fail. Might be used to check that a certain part
of the code is not reached. Or to have a failing test before the
test code is implemented. The String parameter is optional.

assertTrue([message], boolean condition) Checks that the boolean condition is true.

assert False([message], boolean condition) Checks that the boolean condition is false.

assertEquals([String message], expected, Tests that two values are the same. Note: for arrays the
actual) reference is checked not the content of the arrays.

assertEquals([String message], expected, Test that float or double values match. The tolerance is the
actual, tolerance) number of decimals which must be the same.

assertNull([message], object) Checks that the object is null.

assertNotNull([message], object) Checks that the object is not null.

assertSame([String], expected, actual) Checks that both variables refer to the same object.
assertNotSame([String], expected, actual) Checks that both variables refer to different objects.

3.Using junit in eclipse


A unit test targets some other "class under test;" for example, the class ArrayIntListTest
might be targeting the ArrayIntList as its class under test. A unit test generally consists of
various testing methods that each interact with the class under test in some specific way
to make sure it works as expected.

JUnit isn't part of the standard Java class libraries, but it does come included with
Eclipse.

3.1 Creating a JUnit Test Case in Eclipse


Create a Class
Create a java class to be tested say MessageUtil.java

1.Project->New Java Project

2.Add Class Named HelloWorld in this Project

3.Add the following code in this class

/*
* This class prints the given message on console.
*/
publicclassHelloWorld {

privateStringmessage
;

//Constructor
//@param message to be printed
publicHelloWorld(String message){
this.message= message;
}

// prints the message


publicString printMessage(){
System.
out.println(
message
);
returnmessage
;
}
}
Create Test Case Class
• Create a java test class say TestJunit.java.
• Add a test method testPrintMessage() to your test class.
• Add an Annotaion @Test to method testPrintMessage().
• Implement the test condition and check the condition using
assertEquals API of Junit.
importorg.junit.Test;
importstaticorg.junit.Assert.
assertEquals
;

publicclass HelloWorldTest {

Stringmessage= "Hello World"


;
HelloWorld
messageUtil= new HelloWorld(
message
);

@Test
publicvoid testPrintMessage() {
assertEquals(message
,messageUtil
.printMessage());
}
}

Run Test Case Class

Press the Green Play button in menu bar or Right Click->Select Run As-> JUnit Test.
Example 2:

1. Create a new Java Project

2. Add a class named Calculator in this project

publicclassCalculator {

publicint add(int value1,int value2) {


returnvalue1 + value2;
}

publicint multi
ply(int value1,int value2) {
returnvalue1 * value2;
}

publicint subtract(
int value1,int value2) {
returnvalue1- value2;
}

publicint divide(
int value1,int value2) {
returnvalue1 / value2;

}
}

3. Now Right Click on class and Select New ->JUnit Test Case

4. In Option Name -> Specify the test class name and in Option Class under test -
>Specify the Class which you want to test(class calculator in this case).

5. Click Next -> New JUnit Test Case Dialog opens . You can select methods which you
want to test.

6. Click Next.

7. At this point Eclipse will ask whether you want it to automatically attach the JUnit
library to your project. Yes, you do. Select "Perform the following action: Add JUnit 4
library to the build path" and press OK.
8. Now it will show the Test Class CalculatorTest.java and the methods which you are
selected.

9. Fail(“Not yet implemented”) message in each test because you haven’t implemented
any method.

10. Now change the code until it matches the following code:

12. It will show the following output.

13. Test Methods testAdd and testDivide are pass while testSubtract and testMultiply
are fail.
LAB TASKS

1-Carefully examine the above code, correct the errors and then
again run the test class CalculatorTest.java until all the tests are
pass.

2-Write a complete code of calculator using all the methods of


Table 1 and only first five methods of Table 2 specified earlier in
this manual.

You might also like