user387600
user387600

Reputation: 99

How to mock MongoDB repository method in Java

I'm trying to mock the following piece of code in my JUnit test

requestData = requestRepository.findByRequestId(requestId);

by doing

@Mock
RequestRepository requestRepository;

@Mock
RequestData requestData;

Mockito.when(requestRepository.findByRequestId(requestId)).thenReturn(requestData);

But instead of giving the mock object back, i'm getting null value. What is the correct way to mock MongoDB repository methods.

Upvotes: 2

Views: 8295

Answers (2)

Juan Rada
Juan Rada

Reputation: 3766

When using SpringRunner based test, use @MockBean to declare mock of your context beans.

Upvotes: 2

GnanaJeyam
GnanaJeyam

Reputation: 3170

If you don't know about your request id value (it may be a dynamic value) on that case you can use Mock.any(<?>.class).

Example:

Mockito.when(requestRepository.findByRequestId(Long.class)).thenReturn(requestData);

The above example is only for requestId of type Long, if you need integer then you need to change the class to Integer.

Upvotes: 0

Related Questions