IntelliJ IDEA for unit testing


 Please read the previous post if you haven't, Previous (Java Unit Testing with JUnit ).

 We are performing the same test but using IDE. And download IntelliJ IDEA if you haven't.

For this unit testing, i have created new project, no libraries, no template.

  1. Create new directory "test", right click on project > add > directory.
  2. Mark the directory as test sources root.
  3. Create Calculator class, the class is created as , right click on project > add > java class.
    paste the code

    public class Calculator{
        // default values
        double p = 0.0;
        double t = 0.0;
        double r = 0.0;
        // constructor that updates the values
        public Calculator(double p, double t, double r){
            this.p = p;
            this.t = t;
            this.r = r;
        // method that calculates the interest
        public double calculateInterest(){
            return p*t*r / 100;
  4. Create test class for Calculator, press alt & enter on class name > create test.

    Configure JUnit like as this
    Fix and download library
    And the newly created testClass (CalculatorTest) will look like this 
    import org.junit.After;
    import org.junit.Before;
    import org.junit.Test;
    import static org.junit.Assert.*;
    public class CalculatorTest {
        Calculator calculator = null;
        // values for your test case
        double p = 10000.0;
        double t = 1.0;
        double r = 10.0;
        public void setUp() throws Exception {
            calculator = new Calculator(p, t, r);
        public void tearDown() throws Exception {
        public void calculateInterest() {
            assertEquals(1000.0, calculator.calculateInterest(), 0.0);
  5. Create a TestRunner class inside test directory. This will be our entry point to perform all test, paste.

    import org.junit.runner.JUnitCore;
    import org.junit.runner.Result;
    import org.junit.runner.notification.Failure;
    public class TestRunner{
        public static void main(String[] str){
            // Run test classes and grab result
            Result result = JUnitCore.runClasses(CalculatorTest.class);
            // Test result
            // print the failure message if failure
            for(Failure failure : result.getFailures()){
                // print string
  6. Yey, test success.


Popular Posts