[英]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.尝试在 Spring 引导服务中使用 Junit5 Mockito 编写测试用例的方法。 In which, the JPA query returns the data as Optional<Tuple.
其中,JPA 查询返回数据为 Optional<Tuple。
I tried mocking Tuple as below, But it's null.我试过 mocking 元组如下,但它是 null。 How do we create a Mock for Tuple and set the values in it?
我们如何为 Tuple 创建一个 Mock 并在其中设置值?
The JPA call: JPA 调用:
Optional<Tuple> meterDetails = meterDetailsRepo.
getMeterTypeByMeterId(request.getCompanyCode(), request.getMeterId());
Here, I tried mocking for above line of code在这里,我为上面的代码行尝试了 mocking
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?我们如何设置上面的 Tuple (mockTuple) 中的值?
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.首先,您似乎是 mocking 与您上面提到的“JPA 调用”不同的方法。 In one case, the method's name is
getMeterTypeByMeterId
, but when you are setting an expectation with Mockito you are calling getById
.在一种情况下,方法的名称是
getMeterTypeByMeterId
,但是当您使用 Mockito 设置期望时,您正在调用getById
。 I'm not an expert in Mockito, though, I may be confused.我不是 Mockito 方面的专家,不过,我可能会感到困惑。
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?不管以上如何,如果你想要的是 mocking 一个服务中返回某个结果的方法,为什么不创建一个具有预期值的真实
Tuple
,然后使用 Mockito 来模拟方法的执行? Something like:就像是:
Tuple expectedTuple = TupleBuilder.tuple().of("foo", "bar");
Mockito.when(meterDetailsRepo.getById(id).thenReturn(Optional.of(expectedTuple)));
Hope it helps!希望能帮助到你!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.