【问题标题】:how to match the String... use Mockito and PowerMock如何匹配字符串...使用 Mockito 和 PowerMock
【发布时间】:2017-06-13 08:00:25
【问题描述】:

我最近在学习 Mockito 和 PowerMock。

我遇到了以下问题

    //This method belongs to the Messages class
    public static String get(Locale locale, String key, String... args) {
        return MessageSupplier.getMessage(locale, key, args);
    }
    //the new class
    @RunWith(PowerMockRunner.class)
    @PowerMockIgnore( {"javax.management.*"})
    @PrepareForTest({Messages.class, LocaleContextHolder.class})
    public class DiscreT {

        @Test
        public void foo() {

            PowerMockito.mockStatic(LocaleContextHolder.class);
            when(LocaleContextHolder.getLocale()).thenReturn(Locale.ENGLISH);

            PowerMockito.mockStatic(Messages.class);
            when(Messages.get(Mockito.any(Locale.class),Mockito.anyString(), Mockito.any(String[].class)))
                    .thenReturn("123156458");

            System.out.print(Messages.get(LocaleContextHolder.getLocale(), "p1"));

            System.out.print(Messages.get(LocaleContextHolder.getLocale(), "p1", "p2"));

        }
    }

结果:null 123156458

为什么?以及如何匹配字符串...

【问题讨论】:

    标签: mockito junit4 powermock


    【解决方案1】:

    在您的第一个 System.out.print 语句中,您为 Messages.get 方法使用了 2 个参数。这是您模拟的方法的重载之一。这就是它返回 null 的原因。请注意,未模拟其行为的对象模拟将默认返回 null。

    如果你想让 Messages.get(Locale, String) 方法工作,你也必须模拟它

    when(Messages.get(Mockito.any(Locale.class),Mockito.anyString()))
                        .thenReturn("123156458");
    

    请记住,您已经模拟了接受最多参数的方法这一事实并不意味着 Mockito 可以理解并模拟其余的重载!你也必须模拟它们。

    据我所知,无法模拟一次方法并自动模拟其所有重载,但是有一种方法可以创建模拟对象并为其所有方法配置默认响应。查看http://www.baeldung.com/mockito-mock-methods#answer

    【讨论】:

    • 知道了,但无论参数如何,我都找不到任何调用的方法
    • 是的,我也搜索过,似乎不存在。如果需要,有一种方法可以为任何模拟方法添加默认答案,但我找不到所有方法重载的自动模拟。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-31
    • 1970-01-01
    • 2020-05-01
    • 2017-10-28
    • 2018-11-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多