how to handle exceptions in junit

前端 未结 4 1926
鱼传尺愫
鱼传尺愫 2020-12-09 08:14

I wrote some test cases to test some method. But some methods throw an exception. Am I doing it correctly?

private void testNumber(String word, int number) {         


        
4条回答
  •  我在风中等你
    2020-12-09 08:43

    An unexpected exception is a test failure, so you neither need nor want to catch one.

    @Test
    public void canConvertStringsToDecimals() {
        String str = "1.234";
        Assert.assertEquals(1.234, service.convert(str), 1.0e-4);
    }
    

    Until service does not throw an IllegalArgumentException because str has a decimal point in it, that will be a simple test failure.

    An expected exception should be handled by the optional expected argument of @Test.

    @Test(expected=NullPointerException.class)
    public void cannotConvertNulls() {
        service.convert(null);
    }
    

    If the programmer was lazy and threw Exception, or if he had service return 0.0, the test will fail. Only an NPE will succeed. Note that subclasses of the expected exception also work. That's rare for NPEs, but common with IOExceptions and SQLExceptions.

    In the rare case that you want to test for a specific exception message, you use the newish ExpectedException JUnit @Rule.

    @Rule
    public ExpectedException thrown= ExpectedException.none();
    @Test
    public void messageIncludesErrantTemperature() {
        thrown.expect(IllegalArgumentException.class);
        thrown.expectMessage("-400"); // Tests that the message contains -400.
        temperatureGauge.setTemperature(-400);
    }
    

    Now, unless the setTemperature throws an IAE and the message contains the temperature the user was trying to set, the test fails. This rule can be used in more sophisticated ways.


    Your example can best be handled by:

    private void testNumber(String word, int number)
            throws OutOfRangeNumberException {
        assertEquals(word,  service.convert(number));
    }
    
    @Test
    public final void testZero()
            throws OutOfRangeNumberException {
        testNumber("zero", 0);
    }
    

    You can inline testNumber; now, it does not help much. You can turn this into a parametrized test class.

提交回复
热议问题