junit 笔记(一)
来源:互联网 发布:站长工具js格式化 编辑:程序博客网 时间:2024/06/06 05:34
1. Test Suite
当我们写了多个测试类之后,可以将这些个类组织成一个test suite,执行这个test suite就会按照实现定义好的顺序执行所有的test class。
以下就是一个test suite的定义,其中用到注解@RunWith和@SuiteClasses。@SuiteClasses后面定义了test suite所包含的test class,在执行时也按照这个顺序依次执行这些test case。
package com.vogella.junit.first;import org.junit.runner.RunWith;import org.junit.runners.Suite;import org.junit.runners.Suite.SuiteClasses;@RunWith(Suite.class)@SuiteClasses({ MyClassTest.class, MySecondClassTest.class })public class AllTests {}
2.几个需要说明的注解
1)
@Before
public void method()
在每个test之前都要执行的方法。一个@Test就是一个test。主要用来读入输入文件、实例化类等。
2)
@BeforeClass
public static void method()
这个方法只执行依次,而且实在所有test执行之前就要执行完毕。其对应的方法必须时static方法。@AfterClass也要求对应方法为static方法。
3)
@Ignore
如果不想执行某个case,或者执行完毕一个case需要花很长时间时,再不影响核心case执行的前提下,可以用该注解进行标识。
3.Junit static import
如果使用了静态引入后,当我们在调用一个类(eg: Assert)所提供的静态方法(assertEquals())时就不需要再加类名了。官方示例:
// without static imports you have to write the following statementAssert.assertEquals("10 x 5 must be 50", 50, tester.multiply(10, 5));// alteratively define assertEquals as static importimport static org.junit.Assert.assertEquals;// more code// use it without the prefixassertEquals("10 x 5 must be 50", 50, tester.multiply(10, 5));
4.junit实例
创建一个类MyClass:
package com.vogella.junit.first;public class MyClass { public int multiply(int x, int y) { // the following is just an example if (x > 999) { throw new IllegalArgumentException("X should be less than 1000"); } return x * y; }}创建一个测试类,MyClassTest:
package com.vogella.junit.first;import static org.junit.Assert.assertEquals;import org.junit.AfterClass;import org.junit.BeforeClass;import org.junit.Test;public class MyClassTest { @Test(expected = IllegalArgumentException.class) public void testExceptionIsThrown() { MyClass tester = new MyClass(); tester.multiply(1000, 5); } @Test public void testMultiply() { MyClass tester = new MyClass(); assertEquals("10 x 5 must be 50", 50, tester.multiply(10, 5)); }}ps:@Test (expected = Exception.class)如果对应方法执行中抛出的异常不是期待的异常时,该测试case执行失败。这个用来测试方法在某种情况下是否抛出正确期待类型的异常。
总结:本次笔记学习了Junit的一些入门知识,下次将继续学习Junit高级选项,包括参数化测试、Rules、Categories等。还有Mocking技术。
@Test, 返回值必须为void,而且不能有任何参数。
本文主要参考:http://www.vogella.com/tutorials/JUnit/article.html
0 0
- junit 笔记(一)
- 日常笔记----Junit(一)
- 《Junit In Action》学习笔记(一)
- JUnit in action学习笔记(一)
- junit学习笔记一
- junit浅学笔记一
- junit浅学笔记一
- Junit学习笔记(一)
- junit浅学笔记一
- JUnit笔记一
- JUnit测试笔记(一)
- Junit的学习笔记一
- Junit单元测试学习笔记一
- junit学习笔记(一):JUnit的安装和测试原则
- Junit使用指南(一)
- Junit和Ant入门(一) JUnit
- 【Junit】Junit使用教程(一)
- Junit 笔记 一.对方法的测试
- shared_ptr
- macos下如何配置ssh无密码登录
- 【剑指Offer】鸟瞰50题之31 - 40题
- 学习spring MVC的步骤?
- 关于C++ const 的全面总结
- junit 笔记(一)
- ECSHOP 首页根据ID调用单篇文章代码
- Json解析
- window批处理-2.@
- 51单片机IO口仿串口-未完成
- 华为OJ训练 之 括号配对数目问题
- IDL 全局变量
- Android手电筒+闪光灯基本源码
- SourceMonitor: 代码重构的小工具,大用场