使用 Mockito 模拟静态方法

编程入门 行业动态 更新时间:2024-10-25 14:31:46
本文介绍了使用 Mockito 模拟静态方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我编写了一个工厂来生成 java.sql.Connection 对象:

I've written a factory to produce java.sql.Connection objects:

public class MySQLDatabaseConnectionFactory implements DatabaseConnectionFactory { @Override public Connection getConnection() { try { return DriverManager.getConnection(...); } catch (SQLException e) { throw new RuntimeException(e); } } }

我想验证传递给 DriverManager.getConnection 的参数,但我不知道如何模拟静态方法.我在测试用例中使用 JUnit 4 和 Mockito.是否有模拟/验证此特定用例的好方法?

I'd like to validate the parameters passed to DriverManager.getConnection, but I don't know how to mock a static method. I'm using JUnit 4 and Mockito for my test cases. Is there a good way to mock/verify this specific use-case?

推荐答案

使用 PowerMockito在 Mockito 之上.

Use PowerMockito on top of Mockito.

示例代码:

@RunWith(PowerMockRunner.class) @PrepareForTest(DriverManager.class) public class Mocker { @Test public void shouldVerifyParameters() throws Exception { //given PowerMockito.mockStatic(DriverManager.class); BDDMockito.given(DriverManager.getConnection(...)).willReturn(...); //when sut.execute(); // System Under Test (sut) //then PowerMockito.verifyStatic(); DriverManager.getConnection(...); }

更多信息:

  • 为什么 Mockito 不模拟静态方法?莉>

更多推荐

使用 Mockito 模拟静态方法

本文发布于:2023-10-31 04:03:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1544943.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:静态   方法   Mockito

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!