有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在要求谓词作为参数的Mockito方法调用中获取空指针异常

@Mock
RefDataCache refDataCache;

TradingAccountEntity tradingAccountEntity = Mockito.mock(TradingAccountEntity.class, Mockito.RETURNS_DEEP_STUBS);
tradingAccountEntity.setMethod1(65);
tradingAccountEntity.setMethod2(65);
Mockito.when(refDataCache.getTradingAccount(x-> x.getMethod1()==65)).thenReturn(tradingAccountEntity);
Mockito.when(tradingAccountEntity.getMethod2()).thenReturn((long) 65);

在上面的代码中,我得到NullPointerException声明:

java.lang.NullPointerException: Cannot invoke "getMethod1()" because the return value of "getTradingAccount(org.eclipse.collections.api.block.predicate.Predicate)" is null.

我尝试将代码更改为:

Mockito.when(refDataCache.getTradingAccount(65)).thenReturn(tradingAccountEntity);
Mockito.when(tradingAccountEntity.getMethod2()).thenReturn((long) 65);

然后它显示:

java.lang.NullPointerException: Cannot invoke "getMethod2()" because the return value of "getTradingAccount(org.eclipse.collections.api.block.predicate.Predicate)" is null.

我无法理解如何将值传递给getTradingAccount(),以便它不会给出NullPointerException。 请帮忙


共 (0) 个答案