Search code examples
javamockitopowermockito

How to pass param to mocked class method?


I am using mockito to test mu jdk11-springboot application.

My application has class 'ClientRepository' and that has a method called 'findById' which takes a param of type UUID.

SO the method looks like :

 public String findById(UUID id)

Now I mocked the class to test as :

@MockBean
private ClientRepository clientRepo;

Now I am trying to figure out how to pass the UUID param here:

 Mockito.when(clientRepo.findById(UUID id))
            .thenReturn(dslContext.selectFrom(CLIENT).where(CLIENT.ID.eq(UUID.fromString("3e064b19-ef76-4aea-bf82-e9d8d01daf1c"))).fetch());

Can anyone help?


Solution

  • You can use the following construction:

    UUID expected = ...;
    Mockito.when(clientRepo.findById(Mockito.eq(expected))).thenReturn(...);
    

    This can be a good solution if the expected UUID is not the same instance that you configure in the test.

    Another point to consider:

    You seem to use JOOQ but have a mock bean for repository, which means that you probably test some kind of service (business logic layer). In this case maybe you don’t need to work with database at all, just create a string and return in thenReturn part of the mocking configuration