使用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:
本文来自云栖社区合作伙伴“汪子熙”,了解相关信息可以关注微信公众号"汪子熙"。

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。
持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。
转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。
- 上一篇
使用Java JUnit框架里的@SuiteClasses注解管理测试用例
Suppose I have four test cases in my project, the total methods to be tested: 7 Based on the blog Run only given sets of your unit test via @Category, it is possible to organize test methods within THE SAME CLASS to different categories via @Category, that is, the granularity to control which test methods should be executed is method level. There is another annotation @SuiteClasses which can allows us to categorize test classes into different test suites, and once we specify a given test suite t...
- 下一篇
Java注解@Cacheable的工作原理
In order to avoid unnecessary query on database it is a common pattern to define a cache in application layer to cache the query result from database. See one example below. Here the application cache is maintained in a custom class CacheContext. public class AccountService1 { private final Logger logger = LoggerFactory.getLogger(AccountService1.class); private CacheContext<Account> accountCacheContext; public Account getAccountByName(String accountName) { Account result = accountCacheCont...
相关文章
文章评论
共有0条评论来说两句吧...
文章二维码
点击排行
推荐阅读
最新文章
- 设置Eclipse缩进为4个空格,增强代码规范
- SpringBoot2初体验,简单认识spring boot2并且搭建基础工程
- CentOS8编译安装MySQL8.0.19
- Windows10,CentOS7,CentOS8安装Nodejs环境
- CentOS关闭SELinux安全模块
- Windows10,CentOS7,CentOS8安装MongoDB4.0.16
- Linux系统CentOS6、CentOS7手动修改IP地址
- CentOS8,CentOS7,CentOS6编译安装Redis5.0.7
- Docker快速安装Oracle11G,搭建oracle11g学习环境
- Red5直播服务器,属于Java语言的直播服务器