exceptionassertjthrowable

AssertJ assert on Exception covered another Exception


I'm a beginner of AssertJ. I encountered some issue when I use AssertJ to do Unit Testing.

I have a source code as below, to capture an exception and throw another exception.

try {
    Integer.valueOf(valueA);
} catch(Exception e) {
    throw new XXXException("value is not valid", e);
}

My test case as below failed, and I was told wrong exception assert, it's a bit confusing.

Throwable thrown = catchThrowable(() -> {
    contract.init(ctx, "A", "100A", "B", "200");
});
assertThat(thrown).isInstanceOf(XXXException.class);

The error message as below, it seems like the original exception was captured by AssertJ. Anyone can help? Is it a bug or my mistake of AssertJ API usage? Many Thanks.

java.lang.AssertionError: 
Expecting:
  <java.util.IllegalFormatConversionException: d != java.lang.String>
to be an instance of:
  <xxxx.XXXException>
but was:
  <"java.util.IllegalFormatConversionException: d != java.lang.String

Solution

  • Here's my attempt to reproduce the issue, the test passes as expected:

      @Test
      public void test() {
        Throwable thrown = catchThrowable(() -> f());
        assertThat(thrown).isInstanceOf(RuntimeException.class);
      }
    
      private void f() {
        try {
          Integer.valueOf("100A");
        } catch (Exception e) {
          throw new RuntimeException("value is not valid", e);
        }
      }
    

    Can you show us what contract.init is doing?

    Another possibility would be in the stack trace, if it contains a %d somewhere stack trace it might be interpreted by a String.format but hard to say without more details.