java - 在 JUnit / Mockito 测试中使用 Mocked 对象
问题描述
我有一个 JUnit 测试,内容为
public class EventHandlerTest {
@Mock
ThreadPoolExtendedExecutor threadPoolExtendedExecutor;
private EventHandler handler;
private Map<Queue<SenderTask>> subBuffers = new HashMap<>();
@Before
public void setUp() {
// PROBLEM: threadPoolExtendedExecutor null!
handler = new EventHandler(subBuffers, threadPoolExtendedExecutor);
}
}
当我在 setUp 中调用 new 时,我有threadPoolExtendedExecutor=null
. 我想插入一些模拟所以,调用它的方法时threadPoolExtendedExecutor
我没有NullPointer
问题(此时简单的接口模拟对我来说已经足够了)
解决方案
您可以使用(在 setUp 中)简单地模拟它
threadPoolExtendedExecutor = mock(ThreadPoolExtendedExecutor.class);
@Before
public void setUp() {
threadPoolExtendedExecutor = mock(ThreadPoolExtendedExecutor.class);
handler = new EventHandler(subBuffers, threadPoolExtendedExecutor);
}
您也可以让 MockitoJUnitRunner 为您完成:不要忘记通过使用 @InjectMocks 注释在您的测试服务中注入模拟
@RunWith(MockitoJUnitRunner.class)
public class EventHandlerTest {
@Mock
ThreadPoolExtendedExecutor threadPoolExtendedExecutor;
推荐阅读
- matplotlib - 我如何将 y 轴设置为百万?
- java - JavaFX如何检查所有动态添加的文本字段是否为空
- r - R regex / grep / grepl 用于字母后跟破折号和数字
- java - 构建字符串算法
- liferay - 在 Liferay 7.2 中,如何设置角色以仅编辑某些内容页面?
- javascript - 您将如何使用 Javascript 更改值/添加到对象数组内的嵌套对象数据?
- r - 如何在 R 中处理大量时间序列?
- c# - 使用类型参数保存操作的集合 - 无法转换 IEnumerable
到 IEnumerable - javascript - 任何可以模拟 xbox 控制器输入的 node.js 包?包装 ScpDriverInterface dll 失败:/
- adaptive-cards - 发送窗口高度宽度,工具栏=0 menubar=0 在 webex 自适应卡片的 url 中