Skip to content

hasFieldOrPropertyWithValue swallows exceptions thrown by getters, and reports non-existent property instead #3563

Closed

Description

@DidierLoiseau

Describe the bug
If a getter throws an exception, it is not reported in the AssertionError from hasFieldOrPropertyWithValue()

  • assertj core version: 3.26.3
  • java version: 11
  • test framework version: junit 5.10.2

Test case reproducing the bug

import org.junit.jupiter.api.Test;

import static org.assertj.core.api.Assertions.assertThat;

class ThrowingGetterTest {
  @Test
  void test() {
    assertThat(new MyThrowingPojo())
        .hasFieldOrPropertyWithValue("property", "value");
  }

  static class MyThrowingPojo {
    public String getProperty() {
      throw new RuntimeException();
    }
  }
}

Output:

java.lang.AssertionError: 
Expecting
  AssertJTest$MyThrowingPojo@be64738
to have a property or a field named "property"
(static and synthetic fields are ignored)

	at AssertJTest.test(AssertJTest.java:9)
	at java.base/java.lang.reflect.Method.invoke(Method.java:566)
	at java.base/java.util.ArrayList.forEach(ArrayList.java:1541)
	at java.base/java.util.ArrayList.forEach(ArrayList.java:1541)

(no trace of the RuntimeException – note that the test succeeds when getProperty() returns "value")

The problem appears to be that the nice IntrospectionError built by PropertyOrFieldSupport#getSimpleValue() is discarded in org.assertj.core.internal.Objects#assertHasFieldOrProperty().

In my specific case, the object under test was implemented by proxy which was throwing the exception, which makes it really confusing.

Activity

  1. changed the title [-]hasFieldOrPropertyWithValue() eats exceptions thrown by getters and reports non-existent property instead[/-] [+]hasFieldOrPropertyWithValue() eats exceptions thrown by getters, and reports non-existent property instead[/+] on Aug 7, 2024
  2. scordio commented on Aug 7, 2024

    @scordio
    Member

    Thanks for reporting the issue and providing a compact reproducer, @DidierLoiseau!

  3. etrandafir93 commented on Oct 26, 2024

    @etrandafir93
    Contributor

    Hello @scordio, @joel-costigliola,

    I took a quick look over this one. The issue seems to be in Introspection::getPropertyGetter where we catch all exceptions and wrap them within a IntrospectionError which is later treated as if the field is not present.

    If the getters throw an exception, this will be wrapped within an InvocationTargetException_. So, what we can do is check the exception - if needed - rethrow it without wrapping it in our IntrospectionError

    try {
          getter.setAccessible(true);
          getter.invoke(target);
    } catch (InvocationTargetException t) {
          // if getter invocation fails, throw different exception that is not caught by our logic
          throw new GetterInvocationError(formatErrorMessage("Encountered exception when invoking getter for %s in %s", propertyName,
                                                             target), t.getCause());
    } catch (Exception t) {
          // same as it currently works:
          throw new IntrospectionError(formatErrorMessage("Unable to find property %s in %s", propertyName, target), t);
    }

    If this solution seems reasonable, I can raise a PR so you can take a better look into it :)
    Let me know what you think.

  4. joel-costigliola commented on Oct 26, 2024

    @joel-costigliola
    Member

    @etrandafir93 sounds like a good plan to me, please go on with a PR, thanks!

  5. added this to the 3.27.0 milestone on Oct 26, 2024
  6. etrandafir93 commented on Oct 27, 2024

    @etrandafir93
    Contributor

    @joel-costigliola - This will be even simpler than I initially thought.
    We only need to have a different catch block for InvocationTargetException and wrap it into a different runtime ex:

    try {
          getter.setAccessible(true);
          getter.invoke(target);
    + } catch (InvocationTargetException t) {
    +       //  if getter invocation fails, throw a different exception that's not caught by our logic
    +       throw new GetterInvocationError(formatErrorMessage(
    +                 "Encountered exception when invoking getter for %s in %s", propertyName, target), t.getCause());
    +
    } catch (Exception t) {
          throw new IntrospectionError(formatErrorMessage("Unable to find property %s in %s", propertyName, target), t);
    }

    With this change, we'll still use the field as a fallback verification - but only when the getter invocation fails for reflection-related reasons. Basically, for all the other exceptions described here, apart from InvocationTargetException


    On the other hand, I've noticed tests suggesting the original intended behavior was to bypass ANY exception thrown by the getter and verify the field:

    For eg: FieldsOrPropertiesExtractor_extract_Test::should_fallback_to_field_if_exception_has_been_thrown_on_property_access

    In other words, if the getter throws an error we'll check for the field. If the field is also missing (the case described in this issue), we'll return the non-existent property assertion error, swallowing the exception.

    So I guess it's a matter of deciding what the correct behavior would be in this case.

  7. joel-costigliola commented on Oct 27, 2024

    @joel-costigliola
    Member

    I think we want to keep the behavior that if there is no property we should be checking the field, otherwise it's going to be a sneaky breaking change, but if the property exists, and we can't get its value then I think it is reasonable to throw a specific error saying so.

    If I understand your comment correctly, it is what you have done, right ?

  8. etrandafir93 commented on Oct 27, 2024

    @etrandafir93
    Contributor

    As things stand, we initially try to invoke the getter: If there is any sort of exception (regardless if it's a reflection-related exception in the lib or if it's an exception in the tested code, in the getter itself), we'll try to verify the field as a fallback.

    As a result, the behaviour related to invoking the getters seems a bit inconsistent:

    static class MyPojo {
      private String name = "abcd";
      private String address = "abcd";
      private String country = "abcd";
    
      public String getName() {
        throw new RuntimeException("some exception");
      }
      public String getAddress() {
        return "something else";
      }
      String getCountry() {
        return "something else";
      }
    }
    
    @Test
    void test() {
      assertThat(new MyPojo()).hasFieldOrPropertyWithValue("name", "abcd"); // <-- this is passing, is it ok?
      assertThat(new MyPojo()).hasFieldOrPropertyWithValue("address", "abcd"); // <-- this is failing
      // off-topic:
      assertThat(new MyPojo()).hasFieldOrPropertyWithValue("country", "abcd"); // <-- this is passing, package-protected getters are ignored
    }

    As I understand, we want to keep maintaining this behavior, not to introduce a breaking change - correct?

    If I understand your comment correctly, it is what you have done, right ?
    Not yet, but yes - we can go into this direction. Please confirm if I got it right:

    • maintain current behavior
    • if the field is also missing, rethrow the original exception produced by the getter

    PS: Another interesting case I found (and maybe a bit unexpected/counterintuitive) is with the package-protected getters which will always be ignored, but seems to be slightly off-topic here.

  9. joel-costigliola commented on Oct 27, 2024

    @joel-costigliola
    Member

    You got it right, let's leave the package protected case to another discussion so that we tackle one issue at a time

  10. etrandafir93 commented on Nov 1, 2024

    @etrandafir93
    Contributor

    hello @joel-costigliola,

    I have raised a PR for this. I have added a new field to the IntrospectionError class instead of using the cause - to keep the old behavior relying on this cause intact.

    I wrote a few extra lines about the changes PR itself - Let me know what you think.

  11. added a commit that references this issue on Nov 26, 2024
    a2f62b0
  12. changed the title [-]hasFieldOrPropertyWithValue() eats exceptions thrown by getters, and reports non-existent property instead[/-] [+]`hasFieldOrPropertyWithValue` swallows exceptions thrown by getters, and reports non-existent property instead[/+] on Dec 14, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions