PowerMock:模拟静态方法(+在某些特定方法中返回原始值)

编程入门 行业动态 更新时间:2024-10-27 16:25:24
本文介绍了PowerMock:模拟静态方法(+在某些特定方法中返回原始值)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我使用PowerMock 1.4.7和JUnit 4.8.2

I use PowerMock 1.4.7 and JUnit 4.8.2

我只需要模拟一些静态方法而我需要其他方法(来自同类)只是为了返回原始值。 当我用 mockStatic 模拟时,不要在()时执行 .doReturn()所有静态方法返回它们的默认值 - 如返回Object 时返回null或返回boolean时返回false等等。所以我尝试在每个静态方法上显式使用 thenCallRealMethod 来返回默认实现(意味着没有模拟/没有假货)但我不知道如何在每个可能的参数变量上调用它(=我希望每个可能的输入调用原始方法)。我只知道如何模拟具体的参数变化。

I need to mock only some static methods and I want others (from the same class) just to return original value. When I mock with mockStatic and don't call when().doReturn() all static methods return their defaults - like null when returning Object or false when returning boolean...etc. So I try to use thenCallRealMethod explicitly on each static method to return default implementation (means no mocking/ no fakes) but I don't know how to call it on every possible arguments variations (= I want for every possible input call original method). I only know how to mock concrete argument variation.

推荐答案

您可以在静态类上使用间谍并仅模拟特定方法:

You can use a spy on your static class and mock only specific methods:

@RunWith(PowerMockRunner.class) @PrepareForTest(MyStaticTest.MyStaticClass.class) public class MyStaticTest { public static class MyStaticClass { public static String getA(String a) { return a; } public static String getB(String b) { return b; } } @Test public void should_partial_mock_static_class() throws Exception { //given PowerMockito.spy(MyStaticClass.class); given(MyStaticClass.getB(Mockito.anyString())).willReturn("B"); //then assertEquals("A", MyStaticClass.getA("A")); assertEquals("B", MyStaticClass.getA("B")); assertEquals("C", MyStaticClass.getA("C")); assertEquals("B", MyStaticClass.getB("A")); assertEquals("B", MyStaticClass.getB("B")); assertEquals("B", MyStaticClass.getB("C")); } }

更多推荐

PowerMock:模拟静态方法(+在某些特定方法中返回原始值)

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

发布评论

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

>www.elefans.com

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