JUnit–予期される例外テスト

4149 ワード

JUnitでは、予想される例外をテストする3つの方法があります.
  • @Test、オプションの「expected」属性
  • 捕獲を試み、常にfail()
  • である.
  • @Rule ExpectedException

  • PSはJUnit 4.12テストに合格した
    1.@Test予想属性
    例外タイプのみをテストする場合は、次の項目を参照してください.
    Exception1Test.java
    package com.mkyong;
    
    import org.junit.Test;
    import java.util.ArrayList;
    
    public class Exception1Test {
    
        @Test(expected = ArithmeticException.class)
        public void testDivisionWithException() {
            int i = 1 / 0;
        }
    
        @Test(expected = IndexOutOfBoundsException.class)
        public void testEmptyList() {
            new ArrayList<>().get(0);
        }
    
    }

    2.取得を試み、常に失敗()
    これは少し古い派で、JUnit 3で広く使われています.例外タイプと例外の詳細をテストします.以下を参照してください.
    Exception2Test.java
    package com.mkyong;
    
    import org.junit.Test;
    import java.util.ArrayList;
    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(); //remember this line, else 'may' false positive
            } catch (ArithmeticException e) {
                assertThat(e.getMessage(), is("/ by zero"));
    			//assert others
            }
        }
    
        @Test
        public void testEmptyList() {
            try {
                new ArrayList<>().get(0);
                fail();
            } catch (IndexOutOfBoundsException e) {
                assertThat(e.getMessage(), is("Index: 0, Size: 0"));
            }
        }
    
    
    }

    いつまでもfail()を覚えて!テストするローに異常が発生せず、fail()を配置するのを忘れた場合は、テストに合格します(偽肯定).
    3. @Rule ExpectedException
    このExpectedException規則(JUnit 4.7から)は、「2.Try-catch and always fail()」メソッドのように、例外タイプをテストしたり、異常の詳細をテストしたりすることができますが、より優雅な方法で行います.
    Exception3Test.java
    package com.mkyong;
    
    import com.mkyong.examples.CustomerService;
    import com.mkyong.examples.exception.NameNotFoundException;
    import org.junit.Rule;
    import org.junit.Test;
    import org.junit.rules.ExpectedException;
    
    import static org.hamcrest.CoreMatchers.containsString;
    import static org.hamcrest.CoreMatchers.is;
    import static org.hamcrest.Matchers.hasProperty;
    
    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
    package com.mkyong.examples.exception;
    
    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
    package com.mkyong.examples;
    
    import com.mkyong.examples.exception.NameNotFoundException;
    
    public class CustomerService {
    
        public Customer findByName(String name) throws NameNotFoundException {
    
            if ("".equals(name)) {
                throw new NameNotFoundException(666, "Name is empty!");
            }
    
            return new Customer(name);
    
        }
    
    }

    参考文献
  • JUnit Wiki異常テスト
  • Javaカスタム例外例
  • ラベル:junitユニットテスト
    翻訳:https://mkyong.com/unittest/junit-4-tutorial-2-expected-exception-test/