Friday, 6 July 2018

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

No comments:

Post a Comment