如何匹配字符串...使用 Mockito 和 PowerMock

how to match the String... use Mockito and PowerMock

最近在研究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"));

        }
    }

the result : null 123156458

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

在您的第一个 System.out.print 语句中,您为 Messages.get 方法使用了 2 个参数。这是您 not 模拟的方法重载之一。这就是它 return 为空的原因。请注意,尚未模拟其行为的对象模拟将默认 return 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