如何对Exception进行测试?

为什么对Exception进行测试?请移步这里Java中几种Unit Test场景

有一段业务逻辑是提供以下功能:
如果productId是“ABC”,countryCode是“US”,则返回Product对象;
否则抛出自定义的NotFoundException(“Not Found”);

我们通过JUnit测试其中的NotFoundException进行测试,有几种方法呢?

1,使用@Test(expected=…)注解
2,使用ExpectedException
3,如果使用JUnit5,还可以使用assertThrows断言

如下,使用了三种方式来验证自定义的NotFoundException;

import com.self.tt.exception.NotFoundException;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.runners.MockitoJUnitRunner;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import static org.junit.jupiter.api.Assertions.assertThrows;

@RunWith(MockitoJUnitRunner.class)
public class ExceptionTest {

    @InjectMocks
    private ProductService productService;

    @Rule
    public ExpectedException thrown = ExpectedException.none();

    @Test(expected = NotFoundException.class)
    public void use_test_annotation_to_catch_expect_exception() throws NotFoundException {
        productService.query("", "");
    }


    @Test
    public void use_expect_exception_object_to_assert_exception() throws NotFoundException {
        thrown.expect(NotFoundException.class);
        thrown.expectMessage("Not found");

        productService.query("", "");
    }


    @Test
    public void use_junit5_assertThrows_to_assert_NotFoundException(){
        NotFoundException exception = assertThrows(NotFoundException.class, () -> {
            productService.query("", "");
        });

        assertThat(exception.getMessage(), is("Not found"));
    }
}

1,使用@Test(expected=…)注解:use_test_annotation_to_catch_expect_exception();
2,使用ExpectedException:use_expect_exception_object_to_assert_exception();
3,如果使用JUnit5,还可以使用assertThrows断言: use_junit5_assertThrows_to_assert_NotFoundException();

    原文作者:PageThinker
    原文地址: https://www.jianshu.com/p/96e89e3b0455
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞