1

I wrote the following code :

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

    @Test
    public void testMappingException() {


        exception.expect(ArithmeticException.class);

        int x = 1 / 0;
    }

Everything works correctly. Unfortunatelly it is not working correctly in this case:

ObjectMapper mapper = new ObjectMapper();
void add(String json) {

    try {

        X x = mapper.readValue(json, X.class); // exception here

    } catch (JsonParseException e) {
        e.printStackTrace();
    } catch (JsonMappingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return null;
}

========================================================

@Before
public void setUpBeforeClass() {
    jsonTestExcpetion = "{\"aaa\" : \"bbb\"}";
}


@Test
public void testMappingException() {

    MyClass mc = new MyClass();
    exception.expect(UnrecognizedPropertyException.class);
    myClass.add(jsonTestExcpetion);

}

It should catch the exception

com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException

but in fact, exception is thrown normally and tests fails.

Have you got any ideas?

4

1 回答 1

1

异常被捕获在里面add(String)。因此 JUnit 看不到它,也无法对其进行测试。(JUnit 只看到add方法抛出的异常。)

如何测试它?这种方法只有一个副作用会泄漏到方法之外:它会向System.err. 您可以使用系统规则库对此进行测试。

但是,静默捕获异常通常是不好的做法。调用者不知道发生了异常。我建议不要捕获异常:

void add(String json) throws JsonParseException, JsonMappingException, IOException {
    X x = mapper.readValue(json, X.class);
    return null;
}

然后你的测试将起作用。

如果您不喜欢throws方法签名中的 ,可以使用运行时异常包装异常。

void add(String json) {
  try {
    X x = mapper.readValue(json, X.class);
    return null;
  } catch (JsonParseException e) {
    throw new RuntimeException(e);
  } catch (JsonMappingException e) {
    throw new RuntimeException(e);
  } catch (IOException e) {
    throw new RuntimeException(e);
  }
}
于 2014-02-13T22:39:49.420 回答