使用Java JUnit框架里的@Rule注解的用法举例

简介:

Suppose you need to repeatedly execute some test method in your unit test case, for example, you would like to test getPrice based on the first set of test data 5 times in test method test1() while for the second set of test data, only one time should be executed.

The below class RepeatDemoOne is a bad example, where this special LOOP operation is mixed with test method implementation.

Ideally the test method should only contain the pure logic to operate on the method being tested. So we have a better solution RepeatDemoTwo:
It could easily be observed that now the test method test1 and test2 are rather clean: no more for LOOP and System.out.println exist any more.

Instead, I put the LOOP logic and print out operation into class RepeatableRule which implements interface MethodRule. The concrete rule implementation is done by overriding method apply as below:

class RepeatableRule implements MethodRule{  

    int times = 1;  

    String[] testMethods = null;  
      
    RepeatableRule(int times, String[] testMethods){  
        this.times = times;  
        this.testMethods = testMethods;  
    }  
      
    @Override  
    public Statement apply(final Statement base, final FrameworkMethod method, Object target) {  
      return new Statement() {  
         @Override  
         public void evaluate() throws Throwable {  
            int loopTime = 1;  
            if(Arrays.asList(testMethods).contains(method.getName())) {  
                loopTime = times;  
            }    
            for(int i = 0; i < loopTime; i++ ) { 
                base.evaluate(); 
                System.out.println(method.getName() + " executed.");
             }
         }  
      };  
    }  
}  

When I execute this test case, I can get exactly the same result as RepeatDemoOne:

With the help of @Rule, we can achieve the same as @Test(expected=).

For example, we can use an instance of class ExpectedException to manually declare within a test method itself that a test method expects a given type of exception class.

Besides exception, we can also manually specify a sub string which is expected to appear in an error message, and add our custom error message in Junit report if a test method fails. See following code for example:

public class RuleWithException {
    @Rule
    public ExpectedException exp = ExpectedException.none();

    @Test
    public void expectMessage()
    {
        exp.expectMessage("Hello World");
        throw new RuntimeException("Hello World will throw exception.");
    }

    @Test
    public void expectCourse()
    {
        exp.expectCause(new BaseMatcher<IllegalArgumentException>()
        {

            public boolean matches(Object item)
            {
                return item instanceof IllegalArgumentException;
            }

            @Override
            public void describeTo(org.hamcrest.Description description) {
                description.appendText("Expected exception with type IllegalArgumentException "
                        + "raised in test method! ");
            }

        });
        
        Throwable cause = new IllegalArgumentException("Cause Test.");
        throw new RuntimeException(cause);
    }
}

In this example, if we comment out line 46, the customed message defined in method describeTo will be printed out in JUnit console:


本文来自云栖社区合作伙伴“汪子熙”,了解相关信息可以关注微信公众号"汪子熙"。

相关文章
使用Java JUnit框架里的@Rule注解的用法举例
Suppose you need to repeatedly execute some test method in your unit test case, for example, you would like to test getPrice based on the first set of test data 5 times in test method test1() while for the second set of test data, only one time should be executed. The below class RepeatDemoOne is a
使用Java JUnit框架里的@Rule注解的用法举例
|
8天前
|
存储 Java 数据库连接
java多线程之线程通信
java多线程之线程通信
|
9天前
|
安全 Java 开发者
深入理解Java并发编程:线程安全与性能优化
【4月更文挑战第9天】本文将深入探讨Java并发编程的核心概念,包括线程安全和性能优化。我们将详细解析Java中的同步机制,包括synchronized关键字、Lock接口以及并发集合等,并探讨它们如何影响程序的性能。此外,我们还将讨论Java内存模型,以及它如何影响并发程序的行为。最后,我们将提供一些实用的并发编程技巧和最佳实践,帮助开发者编写出既线程安全又高效的Java程序。
22 3
|
12天前
|
设计模式 安全 Java
Java并发编程实战:使用synchronized关键字实现线程安全
【4月更文挑战第6天】Java中的`synchronized`关键字用于处理多线程并发,确保共享资源的线程安全。它可以修饰方法或代码块,实现互斥访问。当用于方法时,锁定对象实例或类对象;用于代码块时,锁定指定对象。过度使用可能导致性能问题,应注意避免锁持有时间过长、死锁,并考虑使用`java.util.concurrent`包中的高级工具。正确理解和使用`synchronized`是编写线程安全程序的关键。
|
10天前
|
Java
Java 并发编程:深入理解线程池
【4月更文挑战第8天】本文将深入探讨 Java 中的线程池技术,包括其工作原理、优势以及如何使用。线程池是 Java 并发编程的重要工具,它可以有效地管理和控制线程的执行,提高系统性能。通过本文的学习,读者将对线程池有更深入的理解,并能在实际开发中灵活运用。
|
8天前
|
算法 Java 开发者
Java中的多线程编程:概念、实现与性能优化
【4月更文挑战第9天】在Java编程中,多线程是一种强大的工具,它允许开发者创建并发执行的程序,提高系统的响应性和吞吐量。本文将深入探讨Java多线程的核心概念,包括线程的生命周期、线程同步机制以及线程池的使用。接着,我们将展示如何通过继承Thread类和实现Runnable接口来创建线程,并讨论各自的优缺点。此外,文章还将介绍高级主题,如死锁的预防、避免和检测,以及如何使用并发集合和原子变量来提高多线程程序的性能和安全性。最后,我们将提供一些实用的性能优化技巧,帮助开发者编写出更高效、更稳定的多线程应用程序。
|
6天前
|
安全 算法 Java
深入理解Java并发编程:线程安全与性能优化
【4月更文挑战第11天】 在Java中,高效的并发编程是提升应用性能和响应能力的关键。本文将探讨Java并发的核心概念,包括线程安全、锁机制、线程池以及并发集合等,同时提供实用的编程技巧和最佳实践,帮助开发者在保证线程安全的前提下,优化程序性能。我们将通过分析常见的并发问题,如竞态条件、死锁,以及如何利用现代Java并发工具来避免这些问题,从而构建更加健壮和高效的多线程应用程序。
|
10天前
|
Java
Java并发编程:深入理解线程池
【4月更文挑战第7天】在现代软件开发中,多线程编程已经成为一种不可或缺的技术。为了提高程序性能和资源利用率,Java提供了线程池这一强大工具。本文将深入探讨Java线程池的原理、使用方法以及如何根据实际需求定制线程池,帮助读者更好地理解和应用线程池技术。
15 0
|
2天前
|
设计模式 运维 安全
深入理解Java并发编程:线程安全与性能优化
【4月更文挑战第15天】在Java开发中,多线程编程是提升应用程序性能和响应能力的关键手段。然而,它伴随着诸多挑战,尤其是在保证线程安全的同时如何避免性能瓶颈。本文将探讨Java并发编程的核心概念,包括同步机制、锁优化、线程池使用以及并发集合等,旨在为开发者提供实用的线程安全策略和性能优化技巧。通过实例分析和最佳实践的分享,我们的目标是帮助读者构建既高效又可靠的多线程应用。
|
4天前
|
Java 程序员 编译器
Java中的线程同步与锁优化策略
【4月更文挑战第14天】在多线程编程中,线程同步是确保数据一致性和程序正确性的关键。Java提供了多种机制来实现线程同步,其中最常用的是synchronized关键字和Lock接口。本文将深入探讨Java中的线程同步问题,并分析如何通过锁优化策略提高程序性能。我们将首先介绍线程同步的基本概念,然后详细讨论synchronized和Lock的使用及优缺点,最后探讨一些锁优化技巧,如锁粗化、锁消除和读写锁等。