首先需要导入相应的jar和安装插件
创建单元测试类:
- public class TestMain {
- @Test
- public void method(){
- System.out.println("我是测试用例1");
- }
-
- @Test
- public void method2(){
- System.out.println("我是测试用例2");
- }
- }
可以点击类前面的测试按钮,或是单个方法前的测试按钮,如果点击类前面的测试按钮,会执行所有的测试用例。
测试方法有以下要求:
* 方法必须是public的
* 不能是静态方法
* 返回值必须是void
* 必须是没有任何参数的方法
通过断言工具类来进行期望值的判定
- public class TestMain {
- @Test
- public void method(){
- System.out.println("我是测试案例!");
- Assert.assertEquals(1, 2); //参数1是期盼值,参数2是实际测试结果值
- }
- }
通过运行代码后,我们发现测试过程中抛出了一个错误,并且IDEA给我们显示了期盼结果和测试结果
其他案例
- @Test
- public void method(){
- int[] arr = {0, 4, 5, 2, 6, 9, 3, 1, 7, 8};
-
- //错误的冒泡排序
- for (int i = 0; i < arr.length - 1; i++) {
- for (int j = 0; j < arr.length - 1 - i; j++) {
- if(arr[j] > arr[j + 1]){
- int tmp = arr[j];
- arr[j] = arr[j+1];
- arr[j+1] = tmp;
- }
- }
- }
-
- Assert.assertArrayEquals(new int[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, arr);
- }
- @Test
- public void method(){
- try (SqlSession sqlSession = MybatisUtil.getSession(true)){
- TestMapper mapper = sqlSession.getMapper(TestMapper.class);
- Student student = mapper.getStudentBySidAndSex(1, "男");
-
- Assert.assertEquals(new Student().setName("小明").setSex("男").setSid(1), student);
- }
- }
通过`@Before`注解来添加测试用例开始之前的前置操作
- @Before
- public void before(){
- System.out.println("测试前置正在初始化...");
- System.out.println("测试初始化完成,正在开始测试案例...");
- }
- @Test
- public void method1() {
- System.out.println("我是测试用例1");
- }
- @Test
- public void method2(){
- System.out.println("我是测试用例2");
- }
输出
测试前置正在初始化...
测试初始化完成,正在开始测试案例...
我是测试用例1
测试前置正在初始化...
测试初始化完成,正在开始测试案例...
我是测试用例2
- public class TestMain {
-
- private SqlSessionFactory sqlSessionFactory;
- @Before
- public void before(){
- System.out.println("测试前置正在初始化...");
- try {
- sqlSessionFactory = new SqlSessionFactoryBuilder()
- .build(new FileInputStream("mybatis-config.xml"));
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- }
- System.out.println("测试初始化完成,正在开始测试案例...");
- }
-
- @Test
- public void method1(){
- try (SqlSession sqlSession = sqlSessionFactory.openSession(true)){
- TestMapper mapper = sqlSession.getMapper(TestMapper.class);
- Student student = mapper.getStudentBySidAndSex(1, "男");
-
- Assert.assertEquals(new Student().setName("小明").setSex("男").setSid(1), student);
- System.out.println("测试用例1通过!");
- }
- }
-
- @Test
- public void method2(){
- try (SqlSession sqlSession = sqlSessionFactory.openSession(true)){
- TestMapper mapper = sqlSession.getMapper(TestMapper.class);
- Student student = mapper.getStudentBySidAndSex(2, "女");
-
- Assert.assertEquals(new Student().setName("小红").setSex("女").setSid(2), student);
- System.out.println("测试用例2通过!");
- }
- }
- }
通过使用`@After`注解即可添加结束动作
- @After
- public void after(){
- System.out.println("测试结束,收尾工作正在进行...");
- }