Test Driven Development With JUnit5. Part-2( Setting up JUnit environment)

This is the second part of the Test Driven Development With JUnit5 series, you can find the part-1 here

PRE-REQUISITES

  • A working knowledge of the Java programming language would be needed.
  • Have JDK 1.8 installed on your system.
  • An Ide that supports maven/gradle.

Setting Up

Create a new maven project with no archetype, open up your pom.xml and type the following code in it:

Or if you are using gradle then use this in your build.gradle:

Let’s do a quick test to make sure our setup is working.  Remember how Test Driven Development works, you write tests for the features first before writing the business logic code, you may have noticed that a new folder was added for us (I’m using Intelli J IDE), src/test/java, this is where our test code will live.  Let’s write a simple test to validate the subtraction operation of a calculator, create a CalculatorTest class (did you notice that the class name ends with ‘Test’, it’s essentially good practice to add the separate Test code from main code and to add the ‘Test’ suffix to a Test Class, maven also uses it to do some pretty good optimizations) .  The CalculatorTest class will contain this code:

In the code above the @Test annotation marks the testSubtract method as a test method, the assertEquals method that we call confirms that the first parameter equals the second parameter, in this case confirming 4 equals to the result of calc.substract(9, 5).

Now that we have written the test for the feature, let’s write the code to actually do the substraction, so in your src/main/java create a new class called Calculator and type the code below:

Run the CalculatorTest class you should see the result of the test as a green line in your IDE output showing 1 test passed, you can find this code here on github

Next in part 3 we will go through the various annotations used in JUnit.

 

 

2 comments on “Test Driven Development With JUnit5. Part-2( Setting up JUnit environment)

  1. I have noticed that your website needs some fresh articles.
    Writing manually takes a lot of time, but there is tool for this time consuming task, search for; unlimited content Wrastain’s
    tools

Leave a Reply

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