Search code examples
javaassertj

Is there an AssertJ predicate to return the original object under test?


I'm testing that a class returns an instance of the same type modified in some way. After initializing the object I want to make verify that starting state. So for example:

CLS cls = new CLS(a, b, c);
assertThat(cls.property1()).isEqualTo(x);
assertThat(cls.property2()).isEqualTo(y);
assertThat(cls.method(n)).predicates();

I'd like to do this more compactly because there are quite a few variations to test. Something like this:

CLS cls = assertThat(new CLS(a, b, c))
    .extracting("property1", "property2").isEqualTo(x,y).getOriginalObject();
assertThat(cls.method(n)).predicates();

This doesn't work without something like getOriginalObject that returns the original object. Is there anything like this in the AssertJ library?


Solution

  • Version 3.27.0 will add a new .actual() API to access the value under test (see #3489).

    However, this won't help in your example as extracting changes the object under test.

    To achieve what you have in mind and assuming that CLS has getters, returns might help:

    CLS cls = assertThat(new CLS(a, b, c))
      .returns(x, from(CLS::getProperty1))
      .returns(y, from(CLS::getProperty2))
      .actual();
    
    // additional code that uses `cls`
    

    Please note that from is an optional syntax sugar.