VictorGram
VictorGram

Reputation: 2661

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?

Upvotes: 0

Views: 106

Answers (3)

Mark Bramnik
Mark Bramnik

Reputation: 42511

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

Upvotes: 1

Kumar V
Kumar V

Reputation: 1660

Passing the value directly for which the mock is expected to return should also work.

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

Upvotes: 1

user7655213
user7655213

Reputation:

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

Use Mockito.eq("your-uuid-goes-here") instead if your mock should only react to specific values.

Upvotes: 1

Related Questions