pramoth / specification-with-projection

Support projections with JpaSpecificationExecutor.findAll(Specification,Pageable) for Spring Data JPA
MIT License
164 stars 56 forks source link

Mocking findAll with Mockito #30

Closed aliounekanoute closed 1 year ago

aliounekanoute commented 1 year ago

Hi, I am using this package for projection with Specification, I am trying to mock the findAll of JpaRepostory with Mockito but I am facing an issue.

This is my Interface:

public interface MyProjectionDto {
    String getName();
    String getGender();
}

This my test:

...
void testFindAll() {
  Page<MyProjectionDto> list= new PageImpl<>(List.of( new MyProjectionDto() {
        String getName() { return "name"};
        String getGender(return "gender");
  }));
  when(myRepository.findAll(any(SpecificationBuilder.class), any(Pageable.class)))).thenReturn(list);
   Page<MyProjectionDto> receivedList = myService.findAll();
}

I don't know what I am doing wrong.

I am having this error

org.mockito.exceptions.misusing.PotentialStubbingProblem: 
Strict stubbing argument mismatch. Please check:
 - this invocation of 'findAll' method:
    myRepository.findAll(
    SpecificationBuilder@79b663b3,
    MyProjectionDto,
    Page request [number: 0, size 5]
);
    -> at MyServiceImpl.findAll(MyServiceImpl.java)
 - has following stubbing(s) with different arguments:
    1. myRepository.findAll(
    null,
    null
);
      -> at MyServiceTests.testFindAll(MyServiceTests.java)
Typically, stubbing argument mismatch indicates user mistake when writing tests.
Mockito fails early so that you can debug potential problem easily.
However, there are legit scenarios when this exception generates false negative signal:
  - stubbing the same method multiple times using 'given().will()' or 'when().then()' API
    Please use 'will().given()' or 'doReturn().when()' API for stubbing.
  - stubbed method is intentionally invoked with different arguments by code under test
    Please use default or 'silent' JUnit Rule (equivalent of Strictness.LENIENT).
For more information see javadoc for PotentialStubbingProblem class.