Junit是用于编写和运行可重复的自动化测试的开源框架,适用于测试整个对象,对象的一部分,交互中的一个方法或者是一些方法,对象之间的交互。可以为我们在开发中实现边编写边测试,及其的方便,这也符合开发的流程。
Junint使用步骤
添加Junit依赖
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
生成测试类
找到要生成测试类的当前位置
选择要生成测试的方法
生成测试类
public class StudentMapperTest {
@Test
public void selectStudentById() {
String resource = "mybatis-config.xml";
InputStream stream = null;
try {
stream = Resources.getResourceAsStream(resource);
} catch (IOException e) {
e.printStackTrace();
}
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(stream);
//获取会话
SqlSession sqlSession = sqlSessionFactory.openSession();
//通过接口获取对象实例
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
//测试接口
Student213 student = studentMapper.selectStudentById(1);
System.out.println(student213);
}
@Test
public void deleteStudentById() {
}
}
Junit注解介绍
常用的注解:
@Before
当写测试方法是,会防线一些方法之前会执行创建相同的对象,可以将其放入before中操作
使用before注解的方法一般是public void 方法名 ,就会在@test方法之前被执行
@Test
tese注解的public void方法将被作为测试用例
Junit每次都会创建一个新的测试实例,然后调用@test注解的方法
@Test
public void deleteStudentById() {
}
@After
如果分配了额外的资源,在测试完成之后需要关闭资源,使用after注解给定一个public void 方法在test注解的方法执行完成之后在执行
SqlSessionFactory sqlSessionFactory = null;
@Before
public void Before(){
System.out.println("before方法执行完成");
}
@Test
public void selectStudentById() {
System.out.println("测试select方法");
SqlSession sqlSession = sqlSessionFactory.openSession();
//通过接口获取对象实例
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
//测试接口
Student213 student = studentMapper.selectStudentById(1);
System.out.println(student);
}
@After
public void after() {
System.out.println("after方法执行结束");
}