test “handled exceptions” junit

2019-08-29 13:28发布

问题:

I have a method with a handled exception:

public boolean exampleMethod(){

    try{
      Integer temp=null;
      temp.equals(null);
      return
      }catch(Exception e){
        e.printStackTrace();
      }
    }

I want to test it

public void test_exampleMethod(){}

I have tried

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

public void test_exampleMethod(){
    expectedException.expect(JsonParseException.class);
    exampleMethod();
}

but that doesnt work because the exception is handled inside.

I also tried

@Test(expected=JsonParseException.class)

but same issue...the exception is handled

I know that I can just do

assertTrue(if(exampleMethod()))

but it will still print the stack trace to the log. I would prefer clean logs...Any suggestions?

回答1:

You cannot test what a method is doing internally. This is completely hidden (unless there are side effects, that are visible outside).

The test can check that for a specific input the method returns a expected output. But you can not check, how this is done. So you have no way to detect if there was a exception that you have handled.

So: either don't handle the exception (let the test catch the exception), or return a special value that tells you about the exception.

Anyway, I hope your real exception handling is more sensible than in your example.



回答2:

If the method does not throw an exception you cannot expect to get one!

Below an example how write a Junit Test for a method that throws an Exception:

class Parser {
    public void parseValue(String number) {
        return Integer.parseInt(number);
    }
}

Normal test case

public void testParseValueOK() {
    Parser parser = new Parser();
    assertTrue(23, parser.parseValue("23"));     
}

Test case for exception

public void testParseValueException() {
    Parser parser = new Parser();
    try {
       int value = parser.parseValue("notANumber");   
       fail("Expected a NumberFormatException");
    } catch (NumberFormatException ex) {
       // as expected got exception
    }
}