JUnit – Parameterized Test

JUnit – Parameterized Test ”; Previous Next JUnit 4 has introduced a new feature called parameterized tests. Parameterized tests allow a developer to run the same test over and over again using different values. There are five steps that you need to follow to create a parameterized test. Annotate test class with @RunWith(Parameterized.class). Create a public static method annotated with @Parameters that returns a Collection of Objects (as Array) as test data set. Create a public constructor that takes in what is equivalent to one “row” of test data. Create an instance variable for each “column” of test data. Create your test case(s) using the instance variables as the source of the test data. The test case will be invoked once for each row of data. Let us see parameterized tests in action. Create a Class Create a java class to be tested, say, PrimeNumberChecker.java in C:>JUNIT_WORKSPACE. public class PrimeNumberChecker { public Boolean validate(final Integer primeNumber) { for (int i = 2; i < (primeNumber / 2); i++) { if (primeNumber % i == 0) { return false; } } return true; } } Create Parameterized Test Case Class Create a java test class, say, PrimeNumberCheckerTest.java. Create a java class file named PrimeNumberCheckerTest.java in C:>JUNIT_WORKSPACE. import java.util.Arrays; import java.util.Collection; import org.junit.Test; import org.junit.Before; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import org.junit.runner.RunWith; import static org.junit.Assert.assertEquals; @RunWith(Parameterized.class) public class PrimeNumberCheckerTest { private Integer inputNumber; private Boolean expectedResult; private PrimeNumberChecker primeNumberChecker; @Before public void initialize() { primeNumberChecker = new PrimeNumberChecker(); } // Each parameter should be placed as an argument here // Every time runner triggers, it will pass the arguments // from parameters we defined in primeNumbers() method public PrimeNumberCheckerTest(Integer inputNumber, Boolean expectedResult) { this.inputNumber = inputNumber; this.expectedResult = expectedResult; } @Parameterized.Parameters public static Collection primeNumbers() { return Arrays.asList(new Object[][] { { 2, true }, { 6, false }, { 19, true }, { 22, false }, { 23, true } }); } // This test will run 4 times since we have 5 parameters defined @Test public void testPrimeNumberChecker() { System.out.println(“Parameterized Number is : ” + inputNumber); assertEquals(expectedResult, primeNumberChecker.validate(inputNumber)); } } Create Test Runner Class Create a java class file named TestRunner.java in C:>JUNIT_WORKSPACE to execute test case(s). import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.Failure; public class TestRunner { public static void main(String[] args) { Result result = JUnitCore.runClasses(PrimeNumberCheckerTest.class); for (Failure failure : result.getFailures()) { System.out.println(failure.toString()); } System.out.println(result.wasSuccessful()); } } Compile the PrimeNumberChecker, PrimeNumberCheckerTest and Test Runner classes using javac. C:JUNIT_WORKSPACE>javac PrimeNumberChecker.java PrimeNumberCheckerTest.java TestRunner.java Now run the Test Runner, which will run the test cases defined in the provided Test Case class. C:JUNIT_WORKSPACE>java TestRunner Verify the output. Parameterized Number is : 2 Parameterized Number is : 6 Parameterized Number is : 19 Parameterized Number is : 22 Parameterized Number is : 23 true Print Page Previous Next Advertisements ”;

JUnit – Ignore Test

JUnit – Ignore Test ”; Previous Next Sometimes it so happens that our code is not completely ready while running a test case. As a result, the test case fails. The @Ignore annotation helps in this scenario. A test method annotated with @Ignore will not be executed. If a test class is annotated with @Ignore, then none of its test methods will be executed. Now let”s see @Ignore in action. Create a Class Create a java class to be tested, say, MessageUtil.java in C:>JUNIT_WORKSPACE. /* * This class prints the given message on console. */ public class MessageUtil { private String message; //Constructor //@param message to be printed public MessageUtil(String message){ this.message = message; } // prints the message public String printMessage(){ System.out.println(message); return message; } // add “Hi!” to the message public String salutationMessage(){ message = “Hi!” + message; System.out.println(message); return message; } } Create Test Case Class Create a java test class, say, TestJunit.java. Add a test method testPrintMessage() or testSalutationMessage() to your test class. Add an Annotaion @Ignore to method testPrintMessage(). Create a java class file named TestJunit.java in C: JUNIT_WORKSPACE. import org.junit.Test; import org.junit.Ignore; import static org.junit.Assert.assertEquals; public class TestJunit { String message = “Robert”; MessageUtil messageUtil = new MessageUtil(message); @Ignore @Test public void testPrintMessage() { System.out.println(“Inside testPrintMessage()”); message = “Robert”; assertEquals(message,messageUtil.printMessage()); } @Test public void testSalutationMessage() { System.out.println(“Inside testSalutationMessage()”); message = “Hi!” + “Robert”; assertEquals(message,messageUtil.salutationMessage()); } } Create Test Runner Class Create a java class file named TestRunner.java in C:>JUNIT_WORKSPACE to execute test case(s). import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.Failure; public class TestRunner { public static void main(String[] args) { Result result = JUnitCore.runClasses(TestJunit.class); for (Failure failure : result.getFailures()) { System.out.println(failure.toString()); } System.out.println(result.wasSuccessful()); } } Compile the MessageUtil, Test case and Test Runner classes using javac. C:JUNIT_WORKSPACE>javac MessageUtil.java TestJunit.java TestRunner.java Now run the Test Runner, which will not run the testPrintMessage() test case defined in the provided Test Case class. C:JUNIT_WORKSPACE>java TestRunner Verify the output. testPrintMessage() test case is not tested. Inside testSalutationMessage() Hi!Robert true Now, update TestJunit in C:>JUNIT_WORKSPACE to ignore all test cases. Add @Ignore at class level. import org.junit.Test; import org.junit.Ignore; import static org.junit.Assert.assertEquals; @Ignore public class TestJunit { String message = “Robert”; MessageUtil messageUtil = new MessageUtil(message); @Test public void testPrintMessage() { System.out.println(“Inside testPrintMessage()”); message = “Robert”; assertEquals(message,messageUtil.printMessage()); } @Test public void testSalutationMessage() { System.out.println(“Inside testSalutationMessage()”); message = “Hi!” + “Robert”; assertEquals(message,messageUtil.salutationMessage()); } } Compile the test case using javac. C:JUNIT_WORKSPACE>javac TestJunit.java Keep your Test Runner unchanged as follows − import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.Failure; public class TestRunner { public static void main(String[] args) { Result result = JUnitCore.runClasses(TestJunit.class); for (Failure failure : result.getFailures()) { System.out.println(failure.toString()); } System.out.println(result.wasSuccessful()); } } Now run the Test Runner, which will not run any test case defined in the provided Test Case class. C:JUNIT_WORKSPACE>java TestRunner Verify the output. No test case is tested. true Print Page Previous Next Advertisements ”;

JUnit – Using Assertion

JUnit – Using Assertion ”; Previous Next Assertion All the assertions are in the Assert class. public class Assert extends java.lang.Object This class provides a set of assertion methods, useful for writing tests. Only failed assertions are recorded. Some of the important methods of Assert class are as follows − Sr.No. Methods & Description 1 void assertEquals(boolean expected, boolean actual) Checks that two primitives/objects are equal. 2 void assertTrue(boolean condition) Checks that a condition is true. 3 void assertFalse(boolean condition) Checks that a condition is false. 4 void assertNotNull(Object object) Checks that an object isn”t null. 5 void assertNull(Object object) Checks that an object is null. 6 void assertSame(object1, object2) The assertSame() method tests if two object references point to the same object. 7 void assertNotSame(object1, object2) The assertNotSame() method tests if two object references do not point to the same object. 8 void assertArrayEquals(expectedArray, resultArray); The assertArrayEquals() method will test whether two arrays are equal to each other. Let”s use some of the above-mentioned methods in an example. Create a java class file named TestAssertions.java in C:>JUNIT_WORKSPACE. import org.junit.Test; import static org.junit.Assert.*; public class TestAssertions { @Test public void testAssertions() { //test data String str1 = new String (“abc”); String str2 = new String (“abc”); String str3 = null; String str4 = “abc”; String str5 = “abc”; int val1 = 5; int val2 = 6; String[] expectedArray = {“one”, “two”, “three”}; String[] resultArray = {“one”, “two”, “three”}; //Check that two objects are equal assertEquals(str1, str2); //Check that a condition is true assertTrue (val1 < val2); //Check that a condition is false assertFalse(val1 > val2); //Check that an object isn”t null assertNotNull(str1); //Check that an object is null assertNull(str3); //Check if two object references point to the same object assertSame(str4,str5); //Check if two object references not point to the same object assertNotSame(str1,str3); //Check whether two arrays are equal to each other. assertArrayEquals(expectedArray, resultArray); } } Next, create a java class file named TestRunner.java in C:>JUNIT_WORKSPACE to execute test case(s). import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.Failure; public class TestRunner2 { public static void main(String[] args) { Result result = JUnitCore.runClasses(TestAssertions.class); for (Failure failure : result.getFailures()) { System.out.println(failure.toString()); } System.out.println(result.wasSuccessful()); } } Compile the Test case and Test Runner classes using javac. C:JUNIT_WORKSPACE>javac TestAssertions.java TestRunner.java Now run the Test Runner, which will run the test case defined in the provided Test Case class. C:JUNIT_WORKSPACE>java TestRunner Verify the output. true Annotation Annotations are like meta-tags that you can add to your code, and apply them to methods or in class. These annotations in JUnit provide the following information about test methods − which methods are going to run before and after test methods. which methods run before and after all the methods, and. which methods or classes will be ignored during the execution. The following table provides a list of annotations and their meaning in JUnit − Sr.No. Annotation & Description 1 @Test The Test annotation tells JUnit that the public void method to which it is attached can be run as a test case. 2 @Before Several tests need similar objects created before they can run. Annotating a public void method with @Before causes that method to be run before each Test method. 3 @After If you allocate external resources in a Before method, you need to release them after the test runs. Annotating a public void method with @After causes that method to be run after the Test method. 4 @BeforeClass Annotating a public static void method with @BeforeClass causes it to be run once before any of the test methods in the class. 5 @AfterClass This will perform the method after all tests have finished. This can be used to perform clean-up activities. 6 @Ignore The Ignore annotation is used to ignore the test and that test will not be executed. Create a java class file named JunitAnnotation.java in C:>JUNIT_WORKSPACE to test annotation. import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; public class JunitAnnotation { //execute before class @BeforeClass public static void beforeClass() { System.out.println(“in before class”); } //execute after class @AfterClass public static void afterClass() { System.out.println(“in after class”); } //execute before test @Before public void before() { System.out.println(“in before”); } //execute after test @After public void after() { System.out.println(“in after”); } //test case @Test public void test() { System.out.println(“in test”); } //test case ignore and will not execute @Ignore public void ignoreTest() { System.out.println(“in ignore test”); } } Next, create a java class file named TestRunner.java in C:>JUNIT_WORKSPACE to execute annotations. import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.Failure; public class TestRunner { public static void main(String[] args) { Result result = JUnitCore.runClasses(JunitAnnotation.class); for (Failure failure : result.getFailures()) { System.out.println(failure.toString()); } System.out.println(result.wasSuccessful()); } } Compile the Test case and Test Runner classes using javac. C:JUNIT_WORKSPACE>javac JunitAnnotation.java TestRunner.java Now run the Test Runner, which will run the test case defined in the provided Test Case class. C:JUNIT_WORKSPACE>java TestRunner Verify the output. in before class in before in test in after in after class true Print Page Previous Next Advertisements ”;

JUnit – Overview

JUnit – Overview ”; Previous Next Testing is the process of checking the functionality of an application to ensure it runs as per requirements. Unit testing comes into picture at the developers’ level; it is the testing of single entity (class or method). Unit testing plays a critical role in helping a software company deliver quality products to its customers. Unit testing can be done in two ways − manual testing and automated testing. Manual Testing Automated Testing Executing a test cases manually without any tool support is known as manual testing. Taking tool support and executing the test cases by using an automation tool is known as automation testing. Time-consuming and tedious − Since test cases are executed by human resources, it is very slow and tedious. Fast − Automation runs test cases significantly faster than human resources. Huge investment in human resources − As test cases need to be executed manually, more testers are required in manual testing. Less investment in human resources − Test cases are executed using automation tools, so less number of testers are required in automation testing. Less reliable − Manual testing is less reliable, as it has to account for human errors. More reliable − Automation tests are precise and reliable. Non-programmable − No programming can be done to write sophisticated tests to fetch hidden information. Programmable − Testers can program sophisticated tests to bring out hidden information. What is JUnit ? JUnit is a unit testing framework for Java programming language. It plays a crucial role test-driven development, and is a family of unit testing frameworks collectively known as xUnit. JUnit promotes the idea of “first testing then coding”, which emphasizes on setting up the test data for a piece of code that can be tested first and then implemented. This approach is like “test a little, code a little, test a little, code a little.” It increases the productivity of the programmer and the stability of program code, which in turn reduces the stress on the programmer and the time spent on debugging. Features of JUnit JUnit is an open source framework, which is used for writing and running tests. Provides annotations to identify test methods. Provides assertions for testing expected results. Provides test runners for running tests. JUnit tests allow you to write codes faster, which increases quality. JUnit is elegantly simple. It is less complex and 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 comb 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 the test is running smoothly, and it turns red when a test fails. What is a Unit Test Case ? A Unit Test Case is a part of code, which ensures that another part of code (method) works as expected. To achieve the desired results quickly, a test framework is required. JUnit is a perfect unit test framework for Java programming language. A formal written unit test case is characterized by a known input and 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. There must be at least two unit test cases for each requirement − one positive test and one negative test. If a requirement has sub-requirements, each sub-requirement must have at least two test cases as positive and negative. Print Page Previous Next Advertisements ”;

JUnit – Basic Usage

JUnit – Basic Usage ”; Previous Next Let us now have a basic example to demonstrate the step-by-step process of using JUnit. Create a Class Create a java class to be tested, say, MessageUtil.java in C:>JUNIT_WORKSPACE /* * This class prints the given message on console. */ public class MessageUtil { private String message; //Constructor //@param message to be printed public MessageUtil(String message){ this.message = message; } // prints the message public String printMessage(){ System.out.println(message); return message; } } 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. Create a java class file name TestJunit.java in C:>JUNIT_WORKSPACE. import org.junit.Test; import static org.junit.Assert.assertEquals; public class TestJunit { String message = “Hello World”; MessageUtil messageUtil = new MessageUtil(message); @Test public void testPrintMessage() { assertEquals(message,messageUtil.printMessage()); } } Create Test Runner Class Create a TestRunner java class. Use runClasses method of JUnitCore class of JUnit to run the test case of the above created test class. Get the result of test cases run in Result Object. Get failure(s) using the getFailures() method of Result object. Get Success result using the wasSuccessful() method of Result object. Create a java class file named TestRunner.java in C:>JUNIT_WORKSPACE to execute test case(s). import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.Failure; public class TestRunner { public static void main(String[] args) { Result result = JUnitCore.runClasses(TestJunit.class); for (Failure failure : result.getFailures()) { System.out.println(failure.toString()); } System.out.println(result.wasSuccessful()); } } Compile the MessageUtil, Test case and Test Runner classes using javac. C:JUNIT_WORKSPACE>javac MessageUtil.java TestJunit.java TestRunner.java Now run the Test Runner, which will run the test case defined in the provided Test Case class. C:JUNIT_WORKSPACE>java TestRunner Verify the output. Hello World true Now update TestJunit in C:>JUNIT_WORKSPACE so that the test fails. Change the message string. import org.junit.Test; import static org.junit.Assert.assertEquals; public class TestJunit { String message = “Hello World”; MessageUtil messageUtil = new MessageUtil(message); @Test public void testPrintMessage() { message = “New Word”; assertEquals(message,messageUtil.printMessage()); } } Let”s keep the rest of the classes as is, and try to run the same Test Runner. import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.Failure; public class TestRunner { public static void main(String[] args) { Result result = JUnitCore.runClasses(TestJunit.class); for (Failure failure : result.getFailures()) { System.out.println(failure.toString()); } System.out.println(result.wasSuccessful()); } } Now run the Test Runner, which will run the test case defined in the provided Test Case class. C:JUNIT_WORKSPACE>java TestRunner Verify the output. Hello World testPrintMessage(TestJunit): expected:<[New Wor]d> but was:<[Hello Worl]d> false Print Page Previous Next Advertisements ”;

JUnit – Suite Test

JUnit – Suite Test ”; Previous Next Test suite is used to bundle a few unit test cases and run them together. In JUnit, both @RunWith and @Suite annotations are used to run the suite tests. This chapter takes an example having two test classes, TestJunit1 & TestJunit2, that run together using Test Suite. Create a Class Create a java class to be tested, say, MessageUtil.java in C:>JUNIT_WORKSPACE. /* * This class prints the given message on console. */ public class MessageUtil { private String message; //Constructor //@param message to be printed public MessageUtil(String message){ this.message = message; } // prints the message public String printMessage(){ System.out.println(message); return message; } // add “Hi!” to the message public String salutationMessage(){ message = “Hi!” + message; System.out.println(message); return message; } } Create Test Case Classes Create a java class file named TestJunit1.java in C:>JUNIT_WORKSPACE. import org.junit.Test; import org.junit.Ignore; import static org.junit.Assert.assertEquals; public class TestJunit1 { String message = “Robert”; MessageUtil messageUtil = new MessageUtil(message); @Test public void testPrintMessage() { System.out.println(“Inside testPrintMessage()”); assertEquals(message, messageUtil.printMessage()); } } Create a java class file named TestJunit2.java in C:>JUNIT_WORKSPACE. import org.junit.Test; import org.junit.Ignore; import static org.junit.Assert.assertEquals; public class TestJunit2 { String message = “Robert”; MessageUtil messageUtil = new MessageUtil(message); @Test public void testSalutationMessage() { System.out.println(“Inside testSalutationMessage()”); message = “Hi!” + “Robert”; assertEquals(message,messageUtil.salutationMessage()); } } Create Test Suite Class Create a java class. Attach @RunWith(Suite.class) Annotation with the class. Add reference to JUnit test classes using @Suite.SuiteClasses annotation. Create a java class file named TestSuite.java in C:>JUNIT_WORKSPACE to execute test case(s). import org.junit.runner.RunWith; import org.junit.runners.Suite; @RunWith(Suite.class) @Suite.SuiteClasses({ TestJunit1.class, TestJunit2.class }) public class JunitTestSuite { } Create Test Runner Class Create a java class file named TestRunner.java in C:>JUNIT_WORKSPACE to execute test case(s). import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.Failure; public class TestRunner { public static void main(String[] args) { Result result = JUnitCore.runClasses(JunitTestSuite.class); for (Failure failure : result.getFailures()) { System.out.println(failure.toString()); } System.out.println(result.wasSuccessful()); } } Compile all the java classes using javac. C:JUNIT_WORKSPACE>javac MessageUtil.java TestJunit1.java TestJunit2.java JunitTestSuite.java TestRunner.java Now run the Test Runner, which will run the test case defined in the provided Test Case class. C:JUNIT_WORKSPACE>java TestRunner Verify the output. Inside testPrintMessage() Robert Inside testSalutationMessage() Hi Robert true Print Page Previous Next Advertisements ”;