前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Junit 实例精讲基础教程(二) 使用@Test+expected、@Rule+ExpectedException模拟方法异常执行的方式

Junit 实例精讲基础教程(二) 使用@Test+expected、@Rule+ExpectedException模拟方法异常执行的方式

作者头像
青山师
发布2023-05-04 20:22:22
2960
发布2023-05-04 20:22:22
举报

在实际业务中,进行单元测试时,我们除了需要测试正常流程和正确的程序功能之外,可能还需要测试异常场景,在Junit中该如何模拟异常场景呢?

在Junit中,通常有3种方式去模拟生产中的异常场景。

  • 使用@Test结合它的属性expected
  • 使用try-catch并且最后使用fail()
  • 使用@RuleExpectedException

1. 使用@Test和其属性expected

Exception1Test.java:

代码语言:javascript
复制
package org.byron4j.spring_mvc_log4j.mock;

import java.util.ArrayList;

import org.junit.Test;

public class Exception1Test {

    /**
     * 如果测试该方法时产生一个ArithmeticException的异常,则表示测试通过
     * 你可以改成int i = 1 / 1;运行时则会测试不通过-因为与你的期望的不符
     */
    @Test(expected = ArithmeticException.class)
    public void testDivisionWithException() {
        int i = 1 / 0;
    }

    /**
     * 运行时抛出一个IndexOutOfBoundsException异常才会测试通过
     */
    @Test(expected = IndexOutOfBoundsException.class)
    public void testEmptyList() {
        new ArrayList<>().get(0);
    }
}

2. try-catch并且总是在块最后加上fail()

Exception2Test.java:

代码语言:javascript
复制
package org.byron4j.spring_mvc_log4j.mock;

import java.util.ArrayList;

import org.junit.Test;

//注意:这是java中的静态引入
import static junit.framework.TestCase.fail;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;

public class Exception2Test {
    @Test
    public void testDivisionWithException() {
        try {
            int i = 1 / 0;

           fail(); 
        } catch (ArithmeticException e) {
            assertThat(e.getMessage(), is("/ by zero"));

        }
    }



    @Test
    public void testEmptyList() {
        try {
            new ArrayList<>().get(0);
            fail();
        } catch (IndexOutOfBoundsException e) {
            assertThat(e.getMessage(), is("Index: 0, Size: 0"));
        }
    }
}

3. 使用@Rule和ExpectedException

ExpectedException从4.7之后才有的,可以让你测试到异常类型和异常信息。可以认为和try-catch+fail(),但是更优雅些。

Exception3Test.java:

代码语言:javascript
复制
package org.byron4j.spring_mvc_log4j.mock;

import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.Matchers.hasProperty;



import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;


public class Exception3Test {
    @Rule
    public ExpectedException thrown = ExpectedException.none();

    @Test
    public void testDivisionWithException() {

        thrown.expect(ArithmeticException.class);
        thrown.expectMessage(containsString("/ by zero"));

        int i = 1 / 0;

    }

    @Test
    public void testNameNotFoundException() throws NameNotFoundException {

        //test type
        thrown.expect(NameNotFoundException.class);

        //test message
        thrown.expectMessage(is("Name is empty!"));

        //test detail
        thrown.expect(hasProperty("errCode"));  //make sure getters n setters are defined.
        thrown.expect(hasProperty("errCode", is(666)));

        CustomerService cust = new CustomerService();
        cust.findByName("");

    }

}

自定义的异常类NameNotFoundException.java:

代码语言:javascript
复制
package org.byron4j.spring_mvc_log4j.mock;

public class NameNotFoundException extends Exception{
    private int errCode;

    public NameNotFoundException(int errCode, String message) {
        super(message);
        this.errCode = errCode;
    }

    public int getErrCode() {
        return errCode;
    }

    public void setErrCode(int errCode) {
        this.errCode = errCode;
    }
}

CustomerService.java:

代码语言:javascript
复制
package org.byron4j.spring_mvc_log4j.mock;



public class CustomerService {
    public Customer findByName(String name) throws NameNotFoundException {

        if ("".equals(name)) {
            throw new NameNotFoundException(666, "Name is empty!");
        }

        return new Customer(name);

    }

    static class Customer{
        private String name;

        public Customer(String name) {
            super();
            this.name = name;
        }


    }
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2016-10-28,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1. 使用@Test和其属性expected
  • 2. try-catch并且总是在块最后加上fail()
  • 3. 使用@Rule和ExpectedException
相关产品与服务
腾讯云服务器利旧
云服务器(Cloud Virtual Machine,CVM)提供安全可靠的弹性计算服务。 您可以实时扩展或缩减计算资源,适应变化的业务需求,并只需按实际使用的资源计费。使用 CVM 可以极大降低您的软硬件采购成本,简化 IT 运维工作。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档