为方法调用的每个实例返回相同的值 [英] Return same value for every instance of a method call

查看:101
本文介绍了为方法调用的每个实例返回相同的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我没有使用PowerMockito而是正常的并试图模仿这样的东西:

Hi I'm not using PowerMockito but normal one and trying to mock something like this:

when(any(File.class).canWrite()).thenReturn(Boolean.FALSE)

但我得到的NullPointerException 。基本上没有模拟特定实例我想模拟文件对象的任何和所有实例返回 FALSE for canWrite()

But I get a NullPointerException. Basically without mocking a specific instance I want to mock any and all instances of a file object to return FALSE for canWrite().

任何人都可以提供帮助吗?我可以模拟对象,但我正在测试的代码是在静态方法中。

Can anyone help? I can mock the object but the code I'm testing is inside a static method.

推荐答案

这是不可能的。对于常规的Mockito,你需要在when()调用中使用一些模拟对象,而不是任何匹配器。

This is not possible. With regular Mockito you need some mock object in the when() call, not an any matcher.

对于你的例子,当你说任何(File.class)

For your example, when you say any(File.class)

when(any(File.class).canWrite()).thenReturn(Boolean.FALSE)

您需要将一个文件对象实例化为模拟

You need to have a file object already instantiated as a Mock

File fileMock = mock(File.class);    
when(fileMock.canWrite()).thenReturn(Boolean.FALSE)

这篇关于为方法调用的每个实例返回相同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆