`
JerryWang_SAP
  • 浏览: 1000946 次
  • 性别: Icon_minigender_1
  • 来自: 成都
文章分类
社区版块
存档分类
最新评论

使用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:

 

 

要获取更多Jerry的原创文章,请关注公众号"汪子熙":

0
0
分享到:
评论

相关推荐

    在JUnit中使用@Rule测试文件和目录Java开发Ja

    在实际开发中,`@Rule`还可以与其他JUnit注解一起使用,如`@BeforeClass`和`@AfterClass`,以确保测试类级别的资源管理。例如,可以创建一个`ClassRule`来初始化一次性的测试环境,如数据库连接池。 总的来说,通过...

    Java单元测试JUnit4.7

    JUnit是Java领域最广泛使用的单元测试框架,它为开发者提供了一种简洁、高效的测试工具。JUnit 4.7是该框架的一个版本,包含了对之前版本的改进和新功能。 在Java开发中,单元测试是对单个或小部分代码进行的功能...

    解决java junit单元测试@Test报错的问题

    同时,了解JUnit的基本用法和最佳实践也能帮助避免这类问题的发生,比如合理组织测试类和测试方法,以及正确使用断言(Assertions)来验证预期结果。在单元测试中,每个测试方法应独立于其他方法,这样可以更好地隔离...

    探索JUnit4扩展:使用Rule

    标题“探索JUnit4扩展:使用Rule”涉及到的是Java单元测试框架JUnit的一个高级特性,即`@Rule`。在Java开发中,单元测试是确保代码质量、可维护性和可靠性的重要手段,而JUnit作为最流行的Java单元测试框架之一,...

    JUnit——Java测试框架

    JUnit,作为Java编程语言的事实上的标准测试框架,其在软件开发中的重要性不容忽视。由著名程序员Kent Beck和Erich Gamma发起,JUnit以其简洁而强大的功能,极大地推动了Java开发中的自动化测试实践。Martin Fowler...

    探索JUnit4扩展:深入Rule

    Rule的使用非常简单,只需在测试类中声明一个Rule字段,并在需要应用该规则的方法上使用`@Rule`注解。例如,JUnit自带的`ExpectedException` Rule可以帮助我们捕获和验证预期的异常: ```java import org.junit....

    java junit包,可以直接下载使用

    Java JUnit 包是用于Java编程中的一个单元测试框架,它极大地简化了对代码功能的验证和调试。JUnit是开源的,由Eclipse基金会维护,是开发者进行单元测试的首选工具。这个压缩包包含了不同版本的JUnit库,包括文档、...

    JUnit框架实现Java单元测试.pdf

    * TestCase 类:当继承了 TestCase 类之后,就可以使用框架的单元测试功能。 * Assert 类:想要验证功能模块是否达到预期的目标,就需要在编写测试用例之后使用 Assert 类。 3. JUnit 框架的应用 * 单元测试:...

    junit框架文件包

    JUnit框架是Java编程语言中最广泛使用的单元测试框架,它为开发者提供了一种便捷的方式来编写可重复执行的测试用例,确保代码的质量和稳定性。在JavaScript的开发环境中,虽然JUnit主要用于Java,但通过一些工具和库...

    junit4 jar包 Java单元测试框架绿色免费版.zip

    JUnit4是Java编程语言中最广泛使用的单元测试框架之一,它为开发者提供了一种方便、高效的方式来验证代码的正确性。这个“junit4 jar包 Java单元测试框架绿色免费版.zip”文件包含的是JUnit4框架的可执行jar包,用于...

    Junit框架--java高级技术

    **Junit框架——Java高级技术** JUnit是一款广泛应用于Java编程中的单元测试框架,它使得开发者能够轻松地编写和运行可重复的、自动化测试用例,从而确保代码的质量和功能的正确性。在Java开发中,掌握JUnit是进行...

    @Unit注解处理实现代码

    在Java编程中,`@Unit` 注解通常指的是 `@JUnit` 或者是与单元测试相关的概念,因为 `JUnit` 是一个广泛使用的Java单元测试框架,它的注解用于标记测试方法。然而,`@Unit` 不是标准的JUnit注解,可能是自定义的或者...

    Java单元测试之JUnit

    在这个"Java单元测试之JUnit"的代码实践中,我们将深入探讨JUnit的基本使用方法以及它在Java项目中的应用。 首先,JUnit是一个开源的、基于Java的测试框架,它允许开发者编写可执行的测试用例来检查代码的功能。...

    Junit中的基本注解(教学视频)

    Junit中的基本注解(教学视频) Junit中的基本注解,是必须掌握的。 @BeforeClass – 表示在类中的任意public static void方法执行之前执行 ...@Test – 使用该注解标注的public void方法会表示为一个测试方法

    Junit简介和扩展

    JUnit3是一种较为传统的测试方式,其基本使用方法如下: 1. **引入TestCase类**:`import junit.framework.TestCase;` 2. **继承TestCase类**:`class Junit3Demo extends TestCase { ... }` 3. **命名测试方法**:...

    Junit_test.rar_JUnit_JUnit测试_junit工具 @test

    JUnit是Java编程语言中最常用的单元测试框架之一,它为开发者提供了编写和运行可重复的、自动化的测试用例的能力。这个名为"Junit_test.rar"的压缩包显然包含了一个关于JUnit的示例程序,旨在帮助学习者更好地理解和...

    @Commponent注解HelloWorld示例

    通常我们会编写一个测试类,使用`@RunWith(SpringJUnit4ClassRunner.class)`和`@ContextConfiguration`注解来启动Spring测试环境,并通过`@Autowired`注入`HelloWorld`bean,然后调用它的方法进行测试。 总结来说,...

    jUnit测试框架jar.zip

    本文将详细介绍JUnit的使用方法、核心概念以及它在软件开发中的重要性。 首先,JUnit是一个开源的测试框架,由Ernst Klimpert和Kent Beck发起,后续由Eclipse基金会维护。它允许程序员编写可执行的测试用例,这些...

Global site tag (gtag.js) - Google Analytics