简体   繁体   中英

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?

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));

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM