Getting started with Junit

In this blog we will see how to setup unit testing for a java project.

Fist create a java project and a simple class. I created a simple class with one method, the method adds two numbers and returns the sum.

Junit_create_project

 

eclipse puts all the source files in folder called src, we will put all the test classes in a folder named test.

Creating Test folder:

Right click on the project -> new -> source folder

name it as test

Junit_create_test_folder

 

Creating a Test Case:

Now we need to create a test class, right click on the BasicMath.java -> New -> Junit Test Case

Junit_Create_test_class

 

The only thing you need change is the Source folder, point it to the test folder we created.

Junit_Create_test_class_1

Click finish, you will be asked to add the JUnit 4 to the build path , click ok.

A new test class will be created, your project should look like something below.

Junit_Create_test_class_1

You can add your test logic in the test method, you can change the test method name to something meaningful. Junit will run all the methods with annotation @Test.

Junit_Create_test_class_1

Run JUnit Test:

You can run the test now, right click on the project ->Run As -> JUnit Test

Junit_Create_test_class_1

 

The test will succeed, you will see a green bar.

Junit_Create_test_class_1

A failure test case looks like the following

Junit_Create_test_class_1

 

Tags:,

Add a Comment

Your email address will not be published. Required fields are marked *