【问题标题】:Mockito with static methods in util classes在实用程序类中使用静态方法的 Mockito
【发布时间】:2014-08-18 10:30:07
【问题描述】:

我试图找到但找不到我要找的东西。是否可以在 mockito 中执行类似以下操作?

when(TestServiceUtil.getTestItem()).thenReturn(someItem);

【问题讨论】:

标签: spring junit mockito


【解决方案1】:

在您的 pom.xml 中,添加以下依赖项:

<dependency> <groupId>org.powermock</groupId> <artifactId>powermock-module-junit4</artifactId> <version>1.5.6</version> <scope>test</scope> </dependency> <dependency> <groupId>org.powermock</groupId> <artifactId>powermock-api-mockito</artifactId> <version>1.5.6</version> <scope>test</scope> </dependency>

在你的测试类之上: @RunWith(PowerMockRunner.class) public class YourClassName

[...] @Before public void beforeTest() throws SQLException { PowerMockito.mockStatic(TestServiceUtil.class);

现在您可以使用(如您所愿): when(TestServiceUtil.getTestItem()).thenReturn(someItem);

最后的话 - 不要过度使用 PowerMockito。专注于干净的、面向对象的代码。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-30
    • 2014-02-02
    相关资源
    最近更新 更多