External resource rule in junit

ExternalResource rule allows you to use any resource in your test without worrying about how to instantiate that resource. Below example explains how you can use ExternalResource test rule in JUnit tests. Note that how we have used before and after methods of ExternalResource to initialize and destroy the external resource respectively.
 
package rules;

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

/**
 * Created by Sagar on 25-04-2016.
 */
public class ExternalResourceRuleTest {

    Database cn = new Database();

    @Rule
    public ExternalResource resource = new ExternalResource() {
        @Override
        protected void before() throws Throwable {
            cn.connect();
        };

        @Override
        protected void after() {
            cn.disconnect();
        };
    };

    @Test
    public void testDatabase() {
        cn.getData();
        System.out.println("code to test database follows");
    }
}

class Database{
    public void connect(){
        System.out.println("Connecting");
    }

    public void disconnect(){
        System.out.println("Dis-connecting");
    }

    public void getData(){
        System.out.println("Getting data");
    }
}

Here is the output of above code.
 
Connecting
Getting data
code to test database follows
Dis-connecting 

Web development and Automation testing

solutions delivered!!