2

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.

7
  • 1
    this is the correct way. Probably you requestId value during test execution is not the same as the one used to mock call. Commented Jan 22, 2020 at 10:55
  • But instead of giving the mock requestData object, its going to the mongodb and fetching data from there. I want it to send back the mock object. Commented Jan 22, 2020 at 11:14
  • I see @Mock will work only if you call MockitoAnnotations.initMocks(this); or if you are using @RunWith(MockitoJUnitRunner.class). If your test is going directly to the db is because probably you are running with SpringRunner which is starting your full application, and this is actually an integration test Commented Jan 22, 2020 at 11:17
  • Yes I'm running with SpringRunner So is there anyway to get mock object instead of actual data from db. Commented Jan 22, 2020 at 11:23
  • 1
    @JuanRada '@MockBean' worked!! Thank you. Commented Jan 28, 2020 at 9:06

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.