Search code examples
javaunit-testingjunitmatcherassertj

How to use `any` matcher with parameters to the object


I am facing a problem with using assertThat(object.method(new SomeClass(someParam))) as a result, the comparison is when actually running the test, the matcher is comparing object references not the contents of the object as equals method isn't overrided.

I don't want to do the following to solve the problem

  • Mock constructor since I want to use the real object where the method is actually called
  • assertThat(object.method(any(SomeClass.class))) since it loosens the test and the parameter someParam is important.

Is there a solution which would do something like the following?

  • assertThat(object.method(any(SomeClass.class, someParam))) where it will match both object calling it with a specific constructor passing the parameter.

Solution

  • Mock constructor since I want to use the real object where the method is actually called

    This is the wrong approach.

    The better approach is to refactor your production code to use dependency injection, separation of concerns and other OO principles. Then it is easy to replace object with a mock and use verify(object).method(eq(parameter));