DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Testing, Tools, and Frameworks
  4. Writing Your Own JUnit Extensions Using @Rule

Writing Your Own JUnit Extensions Using @Rule

Mathieu Carbou user avatar by
Mathieu Carbou
·
Nov. 06, 09 · Interview
Like (1)
Save
Tweet
Share
13.30K Views

Join the DZone community and get the full member experience.

Join For Free

I was surprised to see how many hidden and undocumented features Junit has. In the new release (4.7) you have access to a lot of interesting stuff (still in development for some). One that is really interesting is @Rule.

This annotation allows you to annotate a public field in your test class, which is of type MethodRule. This binding will intercept test method calls like an AOP framework would do and redefine the execution, skip it, or do anything else.

In example, suppose you want to run some concurrency test: you may need to execute your test method on 15 threads each starting at the same time, and then wait for all threads to finish. All this plumbing can now be resumed by one annotation:

@Test
@Concurrent(15)
public void myTestMethod() throws InterruptedException {
System.out.println("Thread " + Thread.currentThread().getName() + " started !");
int n = new Random().nextInt(5000);
System.out.println("Thread " + Thread.currentThread().getName() + " wait " + n + "ms");
Thread.sleep(n);
System.out.println("Thread " + Thread.currentThread().getName() + " finished");

But who manages this annotation ? It will be our ManageRule, and it is used like this:

public final class ConcurrentTest {

@Rule
public ConcurrentRule concurrentRule = new ConcurrentRule();

@Test
@Concurrent(15)
public void myTestMethod() throws InterruptedException {
System.out.println("Thread " + Thread.currentThread().getName() + " started !");
int n = new Random().nextInt(5000);
System.out.println("Thread " + Thread.currentThread().getName() + " wait " + n + "ms");
Thread.sleep(n);
System.out.println("Thread " + Thread.currentThread().getName() + " finished");
}
}

ManageRule are simplier instances that will intercept all test calls. They are mere instance variable that can benefit of parametrization. In example, we may want in a test class to have a ConcurrentRule with a timeout of 10 seconds, and 2 seconds in another class.

In our case, the ConcurrentRule I made simply check if the test method intercepted has a Concurrent annotation. If yes, it will spawn the number of thread requested and launch the test method for each thread.Here is the annotation:

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface Concurrent {
int value() default 10;
}

And the MethodRule implementation:

import org.junit.rules.MethodRule;
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.Statement;
import java.util.concurrent.CountDownLatch;

public final class ConcurrentRule implements MethodRule {
@Override
public Statement apply(Statement statement, final FrameworkMethod frameworkMethod, final Object o) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
Concurrent concurrent = frameworkMethod.getAnnotation(Concurrent.class);
if (concurrent == null)
frameworkMethod.invokeExplosively(o);
else {
final String name = frameworkMethod.getName();
final Thread[] threads = new Thread[concurrent.value()];
final CountDownLatch go = new CountDownLatch(1);
final CountDownLatch finished = new CountDownLatch(threads.length);
for (int i = 0; i < threads.length; i++) {
threads[i] = new Thread(new Runnable() {
@Override
public void run() {
try {
go.await();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
try {
frameworkMethod.invokeExplosively(o);
} catch (Throwable throwable) {
if (throwable instanceof RuntimeException)
throw (RuntimeException) throwable;
if (throwable instanceof Error)
throw (Error) throwable;
RuntimeException r = new RuntimeException(throwable.getMessage(), throwable);
r.setStackTrace(throwable.getStackTrace());
throw r;
} finally {
finished.countDown();
}
}
}, name + "-Thread-" + i);
threads[i].start();
}
go.countDown();
finished.await();
}
}
};
}
}
All the code is available in Mycila sandbox here.

From http://blog.mycila.com

Test method JUnit Testing

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Introduction to Automation Testing Strategies for Microservices
  • How To Build an Effective CI/CD Pipeline
  • Spring Cloud
  • Use Golang for Data Processing With Amazon Kinesis and AWS Lambda

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: