Friday, 6 July 2018

Junit: Create custom rules

You can create a custom rule by implementing 'TestRule' interface.

For example, I created CustomLogger rule, it logs the test case details, before executing actual test case.


CustomLogger.java
package com.sample.customrules;

import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;

public class CustomLogger implements TestRule {

 @Override
 public Statement apply(Statement base, Description description) {
  return new Statement() {
   @Override
   public void evaluate() throws Throwable {
    System.out.println(description.getDisplayName());
    base.evaluate();
   }
  };
 }

}

TestApp.java
package com.sample.test;

import org.junit.Rule;
import org.junit.Test;

import com.sample.customrules.CustomLogger;

public class TestApp {
 @Rule
 public CustomLogger logger = new CustomLogger();
 
 @Test
 public void testCase1() {
  System.out.println("Executing testCase1");
 }

 @Test
 public void testCase2() {
  System.out.println("Executing testCase2");
 }

 
}


When you run TestApp.java, you can able to see below messages in the console.

testCase1(com.sample.test.TestApp)
Executing testCase1
testCase2(com.sample.test.TestApp)
Executing testCase2

Test Case Execution timer
Calculate and print the execution time of a test case.


TestCaseExecutionTimer.java
package com.sample.customrules;

import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;

public class TestCaseExecutionTimer implements TestRule{
 @Override
 public Statement apply(Statement base, Description description) {
  return new Statement() {
   @Override
   public void evaluate() throws Throwable {
    long time1 = System.currentTimeMillis();
    base.evaluate();
    long time2 = System.currentTimeMillis();
    
    System.out.println(description.getMethodName() + " takes " + (time2-time1) + " milliseconds");
   }
  };
 }
}

TestApp.java
package com.sample.test;

import org.junit.Rule;
import org.junit.Test;

import com.sample.customrules.TestCaseExecutionTimer;

public class TestApp {
 @Rule
 public TestCaseExecutionTimer timer = new TestCaseExecutionTimer();

 @Test
 public void testCase1() throws InterruptedException {
  System.out.println("Executing testCase1");
  Thread.sleep(500);
 }

 @Test
 public void testCase2() throws InterruptedException {
  System.out.println("Executing testCase2");
  Thread.sleep(100);
 }

}


Run ‘TestApp.java’, you can able to see below messages in console.

Executing testCase1
testCase1 takes 501 milliseconds
Executing testCase2
testCase2 takes 100 milliseconds


Previous                                                 Next                                                 Home

Junit: ExternalResource rule

ExternalResource rule is used to setup an external (like database connections, sockets, server) resource before test.



TestApp.java

package com.sample.test;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExternalResource;

public class TestApp {
 MyResource resource = new MyResource();

 @Rule
 public ExternalResource externalResource = new ExternalResource() {

  /**
   * Called before executing the test case
   */
  protected void before() throws Throwable {
   resource.init();
  }

  /**
   * Called after executing the test case
   */
  protected void after() {
   resource.destroy();
  }
 };

 @Test
 public void testCase1() {
  System.out.println("testCase1 : " + resource);
  resource.process();
 }

 @Test
 public void testCase2() {
  System.out.println("testCase2 : " + resource);
  resource.process();
 }

 public static class MyResource {
  public void init() {
   System.out.println("Resource initialized");
  }

  public void process() {
   System.out.println("Resource processed");
  }

  public void destroy() {
   System.out.println("Resource destroyed");
  }
 }

}

When you ran TestApp.java, you can able to see below message is console.

Resource initialized
testCase1 : com.sample.test.TestApp$MyResource@5387f9e0
Resource processed
Resource destroyed
Resource initialized
testCase2 : com.sample.test.TestApp$MyResource@30946e09
Resource processed
Resource destroyed



Previous                                                 Next                                                 Home

Thursday, 5 July 2018

How to upgrade Eclipse IDE?

In this post, I am going to show you how to upgrade Eclipse IDE from Oxygen to Photon. Procedure is same for all the versions of Eclipse.

For example, I am using Eclipse Oxygen.



Follow below steps to upgrade to Eclipse Photon using below steps.

Step 1: You first need to add the new release's repository as follows:
Window > Preferences > Install/Update > Available Software Sites

Click on Add button.


Enter the URL of the new repository (for example, http://download.eclipse.org/releases/photon/ for Photon (4.8)).


If you want to upgrade to some other release, then use the below url
http://download.eclipse.org/releases/{ECLIPSE_RELEASE_NAME}

'{ECLIPSE_RELEASE_NAME}' is a placeholder of the release.

Click 'Ok'

Click ‘Apply and Close’.

Step 2: Help > Check for Updates

Once you click on 'Check for Updates', Eclipse contact the remote server for the updates and opens below window (if there are any updates available).


Click on Next button.


Accept the license agreement and click on Finish button.


Eclipse start installing all the available updates.

Once the installations are successful, Eclipse ask you to restart.


Click on ‘Restart Now’ button.

Eclipse photon will start.


Once eclipse open successfully. Go to Help -> About Eclipse IDE


Thats it, Eclipse upgraded successfully.....:)

Previous                                                    Next                                                    Home

Junit: TestName rule: get the test case name under execution

The TestName Rule makes the current test name available inside test method.




Find the below working application.

TestApp.java
package com.sample.test;

import static org.junit.Assert.assertEquals;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestName;

public class TestApp {
 @Rule
 public TestName testName = new TestName();

 @Test
 public void testCase1() {
  assertEquals("testCase1", testName.getMethodName());
 }

 @Test
 public void testCase2() {
  assertEquals("testCase2", testName.getMethodName());
 }

}




Previous                                                 Next                                                 Home

Wednesday, 4 July 2018

Junit: @Timeout rule: Time out for all unit tests

In my previous posts, I explained how to set time out for a specific unit test case using @Test annotation. Apart from this junit provides Timeout rule, it is used to set the timeout for all the test cases.

Example
@Rule
public Timeout globalTimeout = new Timeout(20, TimeUnit.MILLISECONDS);

Above statement sets the timeout to 20 milliseconds for all test cases.

TestApp.java
package com.sample.test;

import java.util.concurrent.TimeUnit;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.Timeout;

public class TestApp {
 @Rule
 public Timeout globalTimeout = new Timeout(20, TimeUnit.MILLISECONDS);

 @Test
 public void testCase1() throws InterruptedException {
  Thread.sleep(10);
 }
 
 @Test
 public void testCase2() throws InterruptedException {
  Thread.sleep(20);
 }
 
 @Test
 public void testCase3() throws InterruptedException {
  Thread.sleep(30);
 }
}

When you ran above application, you can observe testCase3 is failed in the report.



Previous                                                 Next                                                 Home

Junit: TemporaryFolder rule

By using TemporaryFolder rule, you can create temporary files and folders, those can be deleted once the test cases is executed (The execution status pass/fail doesn't matter).

TempFolderTest.java
package com.sample.test;

import static org.junit.Assert.assertEquals;

import java.io.File;
import java.io.IOException;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;

public class TempFolderTest {

 @Rule
 public TemporaryFolder tempFolder= new TemporaryFolder();
 
 @Test
 public void testTempFolder() throws IOException {
  File folder = tempFolder.newFolder("demos");
  File file = tempFolder.newFile("Hello.txt");
  
  assertEquals(folder.getName(), "demos");
  assertEquals(file.getName(), "Hello.txt");
  
 }
 
 
}




Previous                                                 Next                                                 Home

Tuesday, 3 July 2018

Junit: ErrorCollector: Continue test execution even after failure

ErrorCollector rule is used to collect all the incorrect results in a test case by continuing the test execution even after failure.

Find the below working application.

Arithmetic.java
package com.sample.arithmetic;

public class Arithmetic {

 public int add(int a, int b) {
  return a + b + b;
 }
}

ArithmeticTest.java
package com.sample.arithmetic;

import static org.hamcrest.CoreMatchers.equalTo;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ErrorCollector;

/**
 * Test cases follow below naming convention. methodName_input_output format.
 * 
 * @author krishna
 *
 */
public class ArithmeticTest {
 @Rule
 public final ErrorCollector collector = new ErrorCollector();

 @Test
 public void add_diffInputs() {
  Arithmetic arithmetic = new Arithmetic();

  collector.checkThat("2 + 3 is not equal to 5", 5, equalTo(arithmetic.add(2, 3)));
  collector.checkThat("20 + 30 is not equal to 50", 50, equalTo(arithmetic.add(20, 30)));
  collector.checkThat("200 + 300 is not equal to 500", 500, equalTo(arithmetic.add(200, 300)));

 }

}


Run ArithmeticTest.java, you can able to see below kind of error report.






Previous                                                 Next                                                 Home