JUnit Tutorial
Introduction to Junit JUnit Set up JUnit Architecture JUnit Annotations JUnit Fixtures Junit Assertions Junit Categories @Test Annotation Parameters Verification of Exceptions Ignoring tests Time out in JUnit tests Parameterizing tests Test Suite TestWatcher TemporaryFolder ExternalResource Theories in JUnit JUnit Test Runners Execution order of JUnit tests Assumptions in JUnit JUnit and Hamcrest Matchers Running JUnit tests in parallel JUnit and Maven Integration JUnit and Gradle Integration Executing Selenium tests using JUnit test framework Method interceptor and usage JUnit in Intellij IDEA JUnit in EclipseExternal 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!!