JUnit - Tutorial Lars Vogel

Version 1.4 Copyright © 2007 - 2011 Lars Vogel 21.08.2011
Revision History
Revision 0.1-0.5 JUnit description Revision 0.6 - 1.4 bugfixes and enhancements 10.05.2008 - 21.08.2011 Lars Vogel 03.09.2007 Lars Vogel

Unit testing with JUnit
This tutorial explains unit testing with JUnit 4.X. It explains the creation of JUnit tests and how to run them in Eclipse or via own code. Table of Contents
1. Introduction 1.1. Unit Testing 1.2. Unit Testing with JUnit 1.3. Installation of JUnit 2. JUnit with Eclipse 2.1. 2.2. 2.3. 2.4. 2.5. Preparation Create a Java class Create a JUnit test Run your test via Eclipse Run your test via code

3. JUnit (more) in Detail 3.1. Static imports with Eclipse 3.2. Annotations 3.3. Assert statements 4. Thank you 5. Questions and Discussion 6. Links and Literature 6.1. JUnit Resources 6.2. vogella Resources

1. Introduction 1.1. Unit Testing
A unit test is a piece of code written by a developer that tests a specific functionality in the code which is tested. Unit tests can ensure that functionality is working and can be used to validate that this functionality still works after code changes.

To learn more about mock frameworks please see EasyMock Tutorial 1.junit.Xis a test framework which uses annotation to identify the methods which contain tests. Create therefore a new source folder "test" via right mouse click on your project.1. Select the tab source code.Unit testing uses also mocking of objects. See Eclipse IDETutorial to learn how to do this in Eclipse.2.jar from the JUnit website.JUnit.vogella.3. The download contains the "junit-a. select properties and choose the "Java Build Path". Add this library to your Java project and add it to the classpath. 1.runner. Therefore tests should not depend other tests. We want to create the unit tests in a separate folder.x.first".JUnitCore" to run the test. To write a test with JUnit • Annotate a method with @org.Test • Use a method provides by JUnit to check the expected result ofthe code execution versus the actual result You use a tool like Eclipse or the class "org. JUnit assumes that all test methods can be performed in an arbitrary order. Preparation Create a new project "de. Installation of JUnit Download JUnit4. 2. JUnit with Eclipse 2.junit. . Unit Testing with JUnit JUnit 4.tjar" which is the JUnit library.

..first/src Code Style Compiler Editor [ [ [ [ &dd Folder......2.......Mercurial •.vogella.1{ .first" and the following class.Ref actoring :....Resource :.Task Tags ~J...: :. voqella.Run/Debug •.. junit.t I Java Build Path ~ Source Y prOjects_" ~ Libraries bJ~~ .vogella......dit"..junit.l.. . FindBugs de_..... :. $ Included: : de...~ de.. Create the folder "test"....junit..= PrQ...ftrs. Create a Java class Create a package "de.firstjtest (All) (None) (new) :..... package de...: ~ . &emove ffi··Task Repository :..IJalidation L···WikiText D Allow output folders for source folders folder: Default output I de...junit.. first/bin I[ LOK Browse" ... Llnk Source.first....j~~~··B·~j"Id"P~th· ~ ..Builders •. Jevadoc Location ...V. } } ...Project References •.. .:*' Excluded: Native library location: (None) The creation of an separate folder for the test is not mandatory. junit.....voqelle.......t ...Qge_lla. ¢ "'" I I I I IB II <Y{? Order and Export_! ffi·· Google ffi·· Java ffi· Java ffi· Java Source folders on build patb.. voqelle.. I I ® ~ [ Cancel Press "Add folder" then then press "Create new folder"....junit... But it is good advice to keep the test coding separate from the normal coding..junit. int y) { return x / y... first/src 8"'~ :........Server History Settings !..vogella... <Y{? Order and Ex~ Source folders on build patb.. :..te_rties {or I type filter text ... public class Myclass { public int multiply(int x... ffi ~ de.... 2... . .

:: New JU nit Ted JUnit Test Case C<t~e ~~~ Select the name of the new JUnit test case. Create a JUnit test Select your new class. change the source folder to JUnit. junit.Object D setUpBeforeClassO D D tearDownAfterClassO tearDownO I I[ Browse". vogella. Browse". You have the options to specify the class under test and on the next page J to select methods to be tested.2. first Source folder: Package: I de. first. I[ I [ Browse". J ® [ < Back 1[ Next> I[ Finish ][ Cancel I Press next and select the methods which you want to test. Make sure you change the source folder to test. vogella. . MyClass I[ Browse". Name: Superclass: I MyClassTest I java. firsttestll junit. Which method stubs would you like to create? DsetUPO constructor Do you want to add comments? (Configure D Gener ate comments templates and default value here) Class under test: I de. r J J J o New JUnit 3 test @ New JUnit 4 test junit. Select "New JUnit 4 test". r.3. right mouse click and select New ->JUnit Test case.lang. I de. vogella.

: New JU nit T est Casa '-V JUnit 4 is not on the build path. .eselectAll 1 ObjectO getClassO hashCodeO equelsrObject) :. Eclipse will asked you if it should be added to the classpath. for which test method stubs should be created.si~:~~::J Object 9 9 C F [ ~ :2_elect All . Available m.ethods: (.. : :~e m 10.l"~ i G om .Iae bJ~~1 ~ Test Methods Select method.1 multiply(int.-= New JUntt Test C. J[ Cancel . Do you want to add it? ONot o Open the build path property page @ ~Add now P:~d9:.. o ~reate final method stubs o Create tasks for generated test methods ® [ < ~ack ][ [l!ext> J CEir1i5OJ [ Cancel J If you have not yet JUnit in your classpath. int) [ Q.-0 ("0 in :"-0 Q :"-09 () rlnn"n 8 1 method selected.:~::~h~:t9il:9:0i~:g:~~:ti9:6~j JUnit 4 library to the build path [COK Create a test with the following code..

vogella.package de. If you have several tests you can combine them into a test suite.fj 1 Run on Server Test Alt+Shift+XJ Alt+Shift+X.> Junit Test.junit.vogelia. select your test classes.Test. right mouse click-> New-> Other -> JUnit -Test Suite . To create a new test suite. import org. R T Finished after OJ 0 15 seconds Runs: 1/1 i3 Errors: 0 13 Failures: 1 8 a~: de.assertEquals.MyClassTest :-----1] !~~~:t:0:~itip.. } } 5)). assertEquals("Result".junit.:~:i~::~)::! [Runner: JUnit 4] (0.first. This is due to the fact that our multiplier class is currently not working correctly (it does a division instead of multiplication). public class MyclassTest { @Test public void testMultiply() { Myclass tester = new Myclass().4.Assert.:c::~~. II Run As Debug As • -I - ~" ·IIJll 2 JUnit =El [. Fix the bug and re-run test to get a green light.junit. All test in this test suite will then be executed if you run the test suite. import static org.As.01 The test should be failing (indicated via a red bar). 2.first.junit. 50. Run your test via Eclipse Right click on your new test class and select Run. tester.multiply(lO.

.runner.junit.~ Test Case JUnit Test Suite [3 Java 8·[3 JUnit (J) [ < ~ack H tiext >:J [ Einish 1[ Cancel 1 Select next and select the methods you would like to have test created for. .>.Suite. . . Change the coding to the followingto make your test suite run your test.t..junit.Result ". Run your test via code You can also run your test via your own coding.runner. org..junit.class }) public class AllTests { } 2. If you later develop another test you can add it to @Suite. _-----------------------------------------------------------------------------------------------------. The class "org.class) @Suite. Create in your "test" folder a new class "MyTestRunner" with the followingcoding. .Runwith. : This does currently not work for JUnit4. . As a return parameter you receive an object of type" org.runner .JUnitCore" provides the method runClassesO which allows you to run one or several tests classes. This object can be used to retrieve information about the tests and provides information about the failed tests._ .runners.=: New Select a wizard Create a JUnit Test Suite bJ~~1 - <.o testcases. org.SuiteClasses package import import mypackage.suiteClasses( { MyclassTest. See Bug Report .-J ~izards: I JUnit 8 al i···1EJ JUnit L.junit.5. @Runwith(suite. This class will execute your test class and write potential failures to the console.

You can make the JUnit test methods available via the content assists.aecl.assertEquals • org.package import import import public de.tostring())j } } } EKG Machines. • [~. Favorites DeEine a list of static members or types with static members. plus New Windows-Based EKG COBOL Unit Testing using sav. • org.runclasses(MyclassTest. junit. the new innovatiw test tool for COBOL on mainframes Addiscombe Environmental Multi-Disciplinary Noise and Environmental Consultancy EKGMachines.Failurej class MyTestRunner { public static void main(String[] args) { Result result = JUnitCore.junit.uk 3.Resultj org.Assert.• ~. For example this makes the assertTrue.notification.dit . Remove 1 You can now use Content Assist (Ctrl+Space) to add the method and the import. Assert.•~.> Preferences and select Java> Editor> Content Assist> Favorites. propose those static members even if the import is missing.junit.~~~. JUnit (more) in Detail 3.ti.junit.com Burdick. I suggest to add at least the followingnew members.co. Open the Preferences via Window .JUnitCorej org. Welch Allyn H-P.firstj org. ~ org.1.Assert.com www. Static imports with Eclipse JUnit uses a lot of static methods and Eclipse cannot automatically import static imports.g:i~~it . Assert.Assert.println(failure.ytest.assertFalse • org. Marquette.Assert.runner.vogella.nellsavvvtest www..class)j for (Failure failure: result. junit.savignano.junit.junit.assertTrue • org.fail .~~ •. Add then via "New Member" the methods you need.getFailures()) { system.junit.runner.~~~rt •• : org.runner. assertf else [New t1ember I..out. assertFalse and assertEquals method available.junit..junit. assertEquals €) Content assist will [ New lype .

object) Checks if the object is null assertNotNull([message]. actual) Check that both variables refer not to the same object assertTrue([message].3. expected. Will perform the methodf) before each test. e. Annotations The following give an overview of the available annotations in JUnit 4. actual) Check ifboth variables refer to the same object assertNotSame([String]. expected. assertTrue(true). read input data. This can be used to perform time intensive activities for example be used to connect to a database Will perform the method after all tests have finished. initialize the class) Test method must start with test Will perform the method before the start of all tests.g. Annotations Annotation @Test public void methodt) @Before public void methodf) Description Annotation @Test identifies that this method is a test method.X Table 1.2. True assertsEquals([String message]. Note: for arrays the reference is checked actual) not the content of the arrays assertsEquals([String message].class) @Test(timeout=l 00) 3. object) Check if the object is not null assertSame([String]. Tests if the method throws the named exception Fails ifthe method takes longer then 100 milliseconds @After public void methodO @BeforeClass public void methodO @AfterClass public void methodO @Ignore @Test(expected=IllegalArgumentException. the tolerance are the number of decimals actual. expected. tolerance) which must be the same assertNull([message].3. Test if the values are the same. expected.g. useful if the underlying code has been changed and the test has not yet been adapted or if the runtime of this test isjust to long to be included. boolean condition) Check ifthe boolean condition is true. might be usable to check that a certain part ofthe code is not reached. Assert statements The following gives an overview of the available test methods: Table 2. Usage for float and double. Test methods Description Statement fail(String) Let the method fail. This method can prepare the test environment. e. . This can be used to perform clean-up activities for example be used to disconnect to a database Will ignore the test method.

vogella.org/ JUnit Homepage 6.de Google Group. Links and Literature 6. vogella Resources Eclipse RCP Training (German) Eclipse RCP Training with Lars Vogel Android TutorialIntroduction to Android Programming GWT TutorialProgram in Java and compile to JavaScript and HTML Eclipse RCP TutorialCreate native applications in Java JUnit TutorialTest your application Git TutorialPut everything you have under distributed version control system . I have created a short list how to create good questions which might also help you.2.1. please see the vogella FAQ. If you have questions or find an error in this article please use the www. JUnit Resources http://www. Questions and Discussion Before posting questions.4. Thank you Please help me to support this article: 5. 6.junit.

Sign up to vote on this title
UsefulNot useful