单元测验的根本运用
一、环境装备
运用idea IDE 进行单元测验,首要需求装置JUnit 插件。
1.装置JUnit插件过程
File-->settings-->Plguins-->Browse repositories-->输入JUnit-->挑选JUnit Generator V2.0装置。
2.运用JUnit插件
在需求进行单元测验的类中,运用快捷键alt+insert,挑选JUnit test,挑选JUnit4。
二、单元测验
代码Demo:
@Test
public void testAdd() {
assertEquals(2, new UserDao().add(1, 1));
}
1>注意事项:
1、测验办法上面有必要运用@Test注解进行润饰。
2、测验办法有必要运用public void 进行润饰,不能带有任何参数。
3、新建一个源代码目录用来寄存测验代码。
4、测验类的包应该与被测验类的包保持一致。
5、测验单元中的每一个办法有必要独立测验,每个测验办法之间不能有依赖。
6、测验类运用Test做为类名的后缀(非必要)。
7、测验办法运用test作为办法名的前缀(非必要)。
2>错误解析:
1、Failure 一般是单元测验运用的断语办法判别失败引起,阐明预期成果和程序运转成果不一致。
2、error 是有代码反常引起的,他产生于测验代码本身中的Bug。
3、测验用例是不是用来证明你是对的,而是用来证明你没有错。
3>测验流程:
代码Demo:
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
@AfterClass
public static void setUpAfterClass() throws Exception {
}
@Before
public void before() throws Exception {
}
@After
public void after() throws Exception {
}
1、@BeforeClass所润饰的办法在所有办法加载前履行,并且他是静态的在类加载后就会履行该办法,在内存中只要一份实例,适合用来加载装备文件。
2、@AfterClass所润饰的办法在所有办法履行结束之后履行,一般用来进行资源整理,例如封闭数据库衔接。
3、@Before和@After在每个测验办法履行前都会履行一次。
4>常用注解
1、@Test(excepted=XX.class) 在运转时疏忽某个反常。
2、@Test(timeout=毫秒) 允许程序运转的时刻。
3、@Ignore 所润饰的办法被测验器疏忽。
4、RunWith 能够修正测验运转器 org.junit.runner.Runner
5>测验套件
测验套件是安排测验类一同运转的测验类。详细如下:
代码Demo:
@RunWith(Suite.class)
@Suite.SuiteClasses({UserTest1,UserTest2,UserTest3})public class SuiteTest{
}
注意事项:
1、作为测验套件的进口类,类中不能包含任何办法。
2、更改测验运转器Suite.class。
3、将需求运转的测验类放入Suite.SuiteClasses({})的数组中。
6>参数化设置
需求测验的仅仅是测验数据,代码结构是不变的,只需求更改测验数据。
代码Demo:
@RunWith(Parameterized.class)public class parameterTest {
int expected = 0;
int input1 = 0;
int input2 = 0;
@Parameters
public static Collection t() {
return Arrays.asList(new Object[][]{
{3,1,2},
{5,2,3}
});
}
public parameterTest(int expected,int input1,int input2) {
this.expected = expected;
this.input1 = input1;
this.input2 = input2;
}
@Test
public void testAdd() {
assertEquals(expected, UserDao.add(input1,input2));
}
} 详细过程:
1、更改默认的测验运转器为@RunWith(Parameterized.class)。
2、声明变量来寄存预期值和测验值。
3、声明一个返回值为Collection的公共静态办法,并用@Parameters润饰。
4、为测验类声明一个带有参数的公共结构函数,并在其间为他声明变量赋值。
以上是西安Java培训根据IntelliJ IDEA 所整理的单元测试。