Principles of Object Oriented Programming Practical session 2 – part A
Testing The importance of testing: Tests represent requirements: Ensure that product works as user expected. Reduced costs: By discover defects early in the software life cycle. Program Managers often say: “Testing is too expensive.” Not testing is even more expensive You’re going to spend about half of your development budget on testing, whether you want to or not.
Testing methods White-box testing : Black-box testing : Tests internal structures or workings of a program Black-box testing : Examining functionality without any knowledge of internal implementation. Grey-box testing : Involves having knowledge of internal data structures and algorithms for purposes of designing tests, while executing those tests at the user, or black-box level.
Testing levels Unit testing: Integration testing: System testing: The testing of individual software components. Integration testing: Integration testing is any type of software testing that seeks to verify the interfaces between components against a software design. System testing: Tests a completely integrated system to verify that it meets its requirements. Acceptance testing: Test conducted to determine if the requirements of a specification or contract are met.
JUnit JUnit is a testing framework written by Erich Gamma and Kent Beck. It is used by developers who implement unit tests in Java. JUnit is Open Source Software.
Using Eclipse To setup JUnit in Eclipse: Open eclipse. Right click on project. Click on property. Build Path. Configure Build Path and add the junit-4 in the libraries using “Add Libraries…” button.
Using Intellij
Creating a test To test a project: Create a test class on a different package in the project. Import the JUnit package: import org.junit.* Write test using the tags: @Before: Setup the testing object. @Test: The code testing the code. @After: Cleaning up after the test end. Use Asserts function to test the code. Take a look at the Junit API: http://junit.sourceforge.net/javadoc/org/junit/Assert.html
The Junit API
A code to test: package main_pkg; public class Operations { public double div(double x, double y) { if (y == 0) throw new RuntimeException("Can't divide by zero"); return x/y; } {
Writing tests package tests; import main_pkg.Operations; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class OperationsTests { private Operations obj; @Before public void createSub() { obj = new Operations(); } @Test public void testDiv1() { Assert.assertEquals("8 / 4 should be 2", obj.div(8, 4), 2, 0.01); { public void testDiv2() { try { obj.div(10, 0); Assert.fail("Exception expected"); catch (Exception e) { // Success } import org.junit.*;