nikhil raynade
nikhil raynade

Reputation: 1

How to create mock object of such method which return type Optional<Tuple>

Trying to write a test case using Junit5 Mockito in the Spring boot service for the method. In which, the JPA query returns the data as Optional<Tuple.

I tried mocking Tuple as below, But it's null. How do we create a Mock for Tuple and set the values in it?

The JPA call:

Optional<Tuple> meterDetails = meterDetailsRepo.
                    getMeterTypeByMeterId(request.getCompanyCode(), request.getMeterId());

Here, I tried mocking for above line of code


Tuple mockTuple = Mockito.mock(Tuple.class);
        Optional<Tuple> tupleOptional = Optional.ofNullable(mockTuple);
        Mockito.when(meterDetailsRepo.getById(id).thenReturn(tupleOptional);

How do we set the values in Tuple (mockTuple) above?

Upvotes: 0

Views: 996

Answers (2)

Sinhote
Sinhote

Reputation: 48

First of all, it seems you are mocking a different method as the "JPA call" you mention above. In one case, the method's name is getMeterTypeByMeterId, but when you are setting an expectation with Mockito you are calling getById. I'm not an expert in Mockito, though, I may be confused.

Regardless of the above, if what you want is mocking a method in a service to return a certain result, why don't you create a real Tuple with the expected values and then use Mockito to mock the method's execution? Something like:

Tuple expectedTuple = TupleBuilder.tuple().of("foo", "bar");
Mockito.when(meterDetailsRepo.getById(id).thenReturn(Optional.of(expectedTuple)));

Hope it helps!

Upvotes: 1

Felipe Bonfante
Felipe Bonfante

Reputation: 703

You don't need to mock the Tuple, you can simply create it with the builder available:

Tuple testTuple = TupleBuilder.tuple().of("foo", "bar");
Mockito.when(meterDetailsRepo.getById(id)).thenReturn(Optional.of(testTuple));

Upvotes: 2

Related Questions